Wait for prefious statement to get executed in cursor

Ludmil G 101 Reputation points
2021-10-04T15:49:43.467+00:00

I am using a cursor and I need to wait for the @InsertTSQL to finish with the execution before I go to the Update line. How can I do that?

Cursor start

SELECT @InsertTSQL = 'INSERT INTO Test1 (SELECT * FROM Test2 WHERE id = @Iterator IT ApS )';SET @ScopeIdentity = SCOPE_IDENTITY();';

            EXECUTE sp_executesql @InsertTSQL, N'@ScopeIdentity Integer OUT', @ScopeIdentity = @ScopeIdentity OUT;        

            --Update needs to wait until prev execute finish  
            UPDATE Test3 Set ID = @ScopeIdentity WHEE ID = 22  

Cursor ebd

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,597 questions
{count} votes

Accepted answer
  1. Tom Phillips 17,721 Reputation points
    2021-10-04T16:13:52.447+00:00

    SQL executes sequentially. It always waits for the previous command to finish before starting the next command. It is not possible in TSQL to make it NOT wait for the previous command to finish.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. MelissaMa-MSFT 24,186 Reputation points
    2021-10-05T01:34:46.247+00:00

    Hi @Ludmil G ,

    I am using a cursor and I need to wait for the @InsertTSQL to finish with the execution before I go to the Update line.

    Agreed with Tom, it will not go to the update line until the execution finished. Don't worry about it.

    Besides, just as a suggestion, you could also consider to use CTE to read Id columns from Inserted or Deleted tables or using Output Clause as suggested according to your tsql code in order to fetch the identity values.

    Here is a sample trigger code with Output clause for reading inserted identity values. You could check whether it is a little helpful to you.

    Best regards,
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments