TSQL make EXECUTE statement synchronous

心已入冬 提交于 2021-02-05 07:39:16

问题


I have two TSQL EXEC statements

EXECUTE (N'MyDynamicallyGeneratedStoredProcedure') -- return 0 on success
SELECT @errCode = @@ERROR ;

IF (@errCode = 0)
BEGIN
  EXEC 'A Sql Statement using ##temptable created from first', @returnValue
END

How do I make the two EXEC's synchronous? ; Right now the second EXEC does not wait for the first EXECUTE to complete. I tried issuing a WaitFor Delay, It waits but the second EXEC statement is never returing back.

Thanks.

Update, Here is more info:

  1. First execute creates a global temp table and populates it from a complex SELECT query.
  2. Second EXEC is a CLR Stored Procedure that generates a dynamic SP, based on the variables from recently created and populated Global Temp table.

Now the second EXEC, complains that the Global Temp table is not found.

Update 2, Found the issue (And its me!!)

GBN (and others) was point blank on the answer. EXEC IS synchronous. The problem? My understanding of the problem itself.. I had mentioned

  1. EXECUTE (N'MyDynamicallyGeneratedStoredProcedure') -- return 0 on success

It should have been:

1(a) EXECUTE (N'CreateMyDynamicStoredProcedure') -- return 0 on success

1(b) EXECUTE (N'MyDynamicStoredProcedure') -- return 0 on success

I missed that 1(b) was actually executed somewhere else and after step (2) .

(I should go get a life!!)


回答1:


EXECUTE is sychronous. The 2nd one runs after the 1st one. Always.

Do you have multiple connections running the same code? You are using a global temp table that will be visible to all connections so it may look like asyncc execution...




回答2:


As gbn's answer has pointed out, EXECUTE is synchronous.

The problem might be that your SQL Connection object within CRL stored procedure is not in the same context as your batch script. Your global temporary table should have been dropped after running EXECUTE (N'MyDynamicallyGeneratedStoredProcedure')

Make sure that you create your SQLConnection object by passing "context connection=true" Here is the post answer where someone had a similar problem accessing temporary table since SQLConnection was not in the same connection context.

Accessing TSQL created #temp tables from CLR stored procedure. Is it possible?

If your second CRL stored procedure runs through a different connection, CRL sproc will not be able to access the global temp table since it should have been dropped.

Refer to this post on Global Temporary life cycle (when the gloal temp is dropped)
Deleting Global Temporary Tables (##tempTable) in SQL Server



来源:https://stackoverflow.com/questions/741970/tsql-make-execute-statement-synchronous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!