I have 2 stored procedure with dynamic sql (ms sql 2005). First of them create temp table (##Table) and fill data. Second procedure select data from temp-table created from first procedure.
first sp:
set @cmd = 'create table ' + @tableName +
'(ORDERS_DT_ID int' +
...
',WAREHOUSE_RESULT numeric(15, 3)) ' +
' insert into ' + @tableName + ' ( ORDERS_DT_ID, ... WAREHOUSE_RESULT )' +
' select ro.ORDERS_DT_ID, ... ro.WAREHOUSE_RESULT ' +
' from WH_REMAINS_BY_ORDER_FN ( ' + cast(@orderId as varchar(10)) + ' ) as ro '
exec (@cmd)
second sp(for example):
set @cmd = 'select r.ORDERS_DT_ID, ... r.WAREHOUSE_RESULT' +
' from ' + @tableName + ' as r'
exec (@cmd)
where @tableName – input parameter of sp ( = ‘##Table’, for example)
I use that procedures from asp.net mvc application. I call 1st procedure, check temp table from MSSMS (table is exist) then application are stopped on breakpoint (before 2nd sp), next i call 2nd procedure and table not exist (but between 1st and 2nd procedures call table is exist).
var result = dataContext.firstSP(table, orderId).FirstOrDefault(); // create temp table and fill data (+ return status)
var data = dataContext.secondSP( table, orderId ).AsQueryable(); // before execute we have temp table (check from MSSMS) and we have error after execute that code.
if we check temp table in 2nd procedure, we can see that table not exist:
if object_id ( N'tempdb.dbo.' + ltrim(@tableName) ) is null
begin
exec dbo.firstSP @tableName, @orderId
end
Why temp table from first sp dropped when we run second sp?
Global temporary tables are dropped as soon as the creating session ends and it is not being actively queried from another session.
If you want to have control over the lifetime create a permanent table (possibly in
tempdb)