2016-11-15 68 views
0

我已存儲過程訪問臨時表,這給作爲臨時表外存儲過程

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 [email protected] 
If (OBJECT_ID('tempdb..#Welcomes') Is Not Null) Drop Table #Welcomes 
select * into #Welcomes from hello where [email protected] 

end 

現在,我得到2臨時表的結果,我將使用在數據集中輸出..

現在我需要訪問此#welcome在另一個存儲過程..我的意思是在存儲過程中創建

Create Proc HelloThere(@ids int,@name nvarchar(10)) 
    as 
    begin 
     exec hello @id = @ids ,@name [email protected] 

     //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 
+3

臨時表是在過程之間共享數據的一種方式,但不是唯一的方式,並不總是最好的方式。請參閱[這裏](http://www.sommarskog.se/share_data.html)以獲取完整的概述,包括如何爲此使用臨時表。 –

+0

謝謝Jereon非常有幫助和信息 – havin

回答

2

臨時表時,在存儲過程完成,所以日被自動刪除臨時表將不可用於調用存儲過程。保持臨時表周圍

一種方法是明確創建在調用PROC表(使用CREATE TABLESELECT INTO),然後在所謂PROC加載:

CREATE PROC Hello @id int,@name nvarchar(30) 
AS 
INSERT INTO #Welcome SELECT * FROM hello where [email protected]; 
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 [email protected]; 

SELECT * FROM #welcome INNER JOIN Atable ON #welcome.id=Atable.idl 

GO 

由於@JeroenMostert在評論中提到,你可以細讀http://www.sommarskog.se/share_data.htmlHow to Share Data between Stored Procedures其他技術。