Thursday, October 20, 2011

How to share Temp table data between stored procs

a local temporary table created in stored proc sp1 is visible only in that same stored proc as well
as in any stored proc called by sp1 directly or indirectly, that is it is a child in the calling
hierarchy of sp1.
The temporary table will not be visible in stored procs that are not called by sp1 directly or indirectly,
that is they are outside of the calling hierarchy of sp1.
Examples
create PROCEDURE [dbo].[test01]
as begin

insert #temp_test01(id) values(1)
insert #temp_test01(id) values(2)
insert #temp_test01(id) values(3)
select * from #temp_test01
end

create PROCEDURE [dbo].[test02]
as begin
select * from #temp_test01
end

begin
create table #temp_test01(id int)
exec dbo.test01 -- if the table is created in here, then dbo.test02 should be called from inside
-- test01, otherwise it won't see the table

exec dbo.test02
end



Same goes for dynamic SQLs. The execution context of exec(SQL) is different from the execution context
of the host stored procedure, thus a temp table crate inside the dynamic SQL cannot be seen in the
stored proc itself that executes the dynamic sql.
In case the columns of the temp table are not known upfront, one can create the temp table with static sql
then add the columns to it with dynamic sql.


begin --

drop table #temp_test01

create table #temp_test01(id int)

end

declare @sql varchar(2000)
select @sql = 'alter table #temp_test01 add id2 int '
exec (@sql)
select @sql = 'insert into #temp_test01 values (100, 200) '
exec (@sql)

exec dbo.test01
exec dbo.test02
end

No comments:

Post a Comment