Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6601911
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T18:48:51+00:00 2026-05-25T18:48:51+00:00

I have ‘ inherited ‘ a brilliant piece of TSQL code that does this:

  • 0

I have ‘inherited‘ a brilliant piece of TSQL code that does this:

  • Loops row-by-row over a cursor.
  • The cursor contains data that need to be merged (Upserted) in Table A
  • For each row loop in the cursor a stored proc is called. The proc:
    • If a corresponding row exists in Table A then it is updated
    • If such a row does not exist then:
      • Inserts a single row in in a different Table B.
      • Fetches the newly generated ID (say its called IDB)
      • Inserts a single row in Table A. Table A insertions need an IDB (the field is not null, it is supposed to have values ONLY from table B, but no FK constraint is in place)

Obviously this sucks (performance & elegance reasons)!!

Question
At first this looks like a standard case of MERGE usage. I tried doing:

MERGE [dbo].[TableA] AS Target
USING <cursor data set as a select statement> as Src on target.IDA = Src.IDA
WHEN MATCHED 
  //update
WHEN NOT MATCHED
//insert <------ Fails because obviously a new IDB is required

Also tried various approaches like a nested select that sends IDB on the OUTPUT but it fails because IDB is a PK.

Other kinds of merges also failed eg:

MERGE Table A with <cursor data set as a select statement>
...
MERGE Table A with Table B
WHEN NOT MATCHED
//insert on Table A
WHEN NOT MATCHED
// Update Table B

Does anyone have an idea on this? Essentially I think if we generalise the question would be:

Can I insert and return the PK in one statement that can be nested in other statements

Thanks in advance for any replies

George

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T18:48:51+00:00Added an answer on May 25, 2026 at 6:48 pm

    If you have an autogenerated PK on TableB, you can use code similar to this. Otherwise, just change the INSERT into TableA to grab the PK from TableB first.

    DECLARE @OldData CHAR(10)
    SET @OldData = 'Old'
    DECLARE @NewData CHAR(10)
    SET @NewData = 'New'
    
    CREATE TABLE #TableA 
    (
        IDA INT IDENTITY(1,1) PRIMARY KEY,
        IDB INT NOT NULL,
        DataA CHAR(10)
    )
    
    CREATE TABLE #TableB 
    (
        IDB INT IDENTITY(1,1) PRIMARY KEY,
        DataB CHAR(10)
    )
    
    DECLARE @IDsToUpsert TABLE
    (
        ID INT
    )
    
    -- Add test values for existing rows 
    INSERT INTO #TableB
    OUTPUT INSERTED.IDB, @OldData
    INTO #TableA
    SELECT @OldData UNION ALL
    SELECT @OldData UNION ALL
    SELECT @OldData UNION ALL
    SELECT @OldData 
    
    -- Add test values for the rows to upsert
    INSERT INTO @IDsToUpsert
    SELECT 1 UNION -- exists
    SELECT 3 UNION -- exists
    SELECT 5 UNION -- does not exist
    SELECT 7 UNION -- does not exist
    SELECT 9       -- does not exist
    
    -- Data Before
    SELECT * From #TableA
    SELECT * From #TableB
    
    DECLARE rows_to_update CURSOR
        FOR SELECT ID FROM @IDsToUpsert
    
    DECLARE @rowToUpdate INT
    DECLARE @existingIDB INT
    
    OPEN rows_to_update;
    
    FETCH NEXT FROM rows_to_update 
    INTO @rowToUpdate;
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        BEGIN TRANSACTION
    
            IF NOT EXISTS 
            (
                SELECT 1 FROM #TableA WITH (UPDLOCK, ROWLOCK, HOLDLOCK)
                WHERE IDA = @rowToUpdate            
            )
            BEGIN
                -- Insert into B, then insert new val into A
                INSERT INTO #TableB
                OUTPUT INSERTED.IDB, INSERTED.DataB 
                INTO #TableA
                SELECT @NewData
                -- Change code here if PK on TableB is not autogenerated
            END
            ELSE
            BEGIN
                -- Update
                UPDATE #TableA
                SET DataA = @NewData
                WHERE IDA = @rowToUpdate
            END
    
        COMMIT TRANSACTION
    
        FETCH NEXT FROM rows_to_update 
        INTO @rowToUpdate;
    END
    
    CLOSE rows_to_update;
    DEALLOCATE rows_to_update;
    
    SELECT * FROM #TableA
    SELECT * FROM #TableB
    
    DROP TABLE #TableA
    DROP TABLE #TableB
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
Have following Java code,that creates StringBuilder with \n,i.e. carriage return delimiters: while (scanner.hasNextLine()){ sb.append(scanner.nextLine()).append(\n);
Have same challenge as this guy: How to copy dependencies to gae war/WEB-INF/lib Applying
have a wierd issue. for the life of me can't trace this back (its
Have a slight problem. Trying to post XML to a server. To do this,
Have been searching all over the internet but struggling to find my answer to
have tried a few different approaches to this but with no success so far.
Have a problem with fscanf() - it does not skip to the next word
Have set up a small website for a client however contact form submissions are
Have been writing the shell script such as : #! /bin/bash `sqlplus -s <username>/<passwd>@dbname`

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.