我有存储过程,它将输出作为临时表
Create Proc Hello (@id int,@name nvarchar(30))
as
begin
If (OBJECT_ID('tempdb..#Welcome') Is Not Null) Drop Table #Welcome
select * into #Welcome from hello where id=@id
If (OBJECT_ID('tempdb..#Welcomes') Is Not Null) Drop Table #Welcomes
select * into #Welcomes from hello where name=@name
end
现在我得到2个临时表作为结果,我将在数据集中使用..
现在我需要在另一个存储过程中访问这个#welcome。我的意思是
Create Proc HelloThere(@ids int,@name nvarchar(10))
as
begin
exec hello @id = @ids ,@name =@name
//select * from #Welcome(Here i need to access the #Welcome so i can perform inner join something like below//
select * from #welcome inner join Atable on #welcome.id=Atable.id
end
答案 0 :(得分:2)
存储过程中创建的临时表会在存储过程完成时自动删除,因此临时表将无法用于调用存储过程。
保持临时表的一种方法是在调用proc中显式创建表(使用CREATE TABLE
或SELECT INTO
),然后将其加载到被调用的proc中:
CREATE PROC Hello @id int,@name nvarchar(30)
AS
INSERT INTO #Welcome SELECT * FROM hello where id=@id;
GO
CREATE PROC HelloThere(@ids int,@name nvarchar(10))
AS
If OBJECT_ID(N'tempdb..#Welcome', 'U') IS NOT NULL DROP TABLE #Welcome;
SELECT * INTO #welcome FROM hello WHERE 0 = 1;
EXEC hello @id = @ids ,@name =@name;
SELECT * FROM #welcome INNER JOIN Atable ON #welcome.id=Atable.idl
GO
正如@JeroenMostert在评论中提到的那样,您可以仔细阅读http://www.sommarskog.se/share_data.html How to Share Data between Stored Procedures以获取其他技巧。