views:

767

answers:

2

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!!)

+5  A: 

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...

gbn
+1  A: 

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

Sung Meister