将值存储在临时表中

时间:2016-09-15 08:09:41

标签: sql sql-server tsql dynamic-sql

如何将以下查询的结果放在临时表中?

以下查询为我提供了一些结果集。我需要将结果集存储在临时表中,以便我可以使用该临时表执行某些连接

Declare @cols nvarchar(max),@query nvarchar(max)
select @cols = 
stuff( ( select  ',[' + Ltrim(rtrim(costelement)) +']' from WECCostElementsCalculation  FOR XML PATH('')),1,1,'');

select @query= 
'with T as 
(select wch.WECCostElementHeaderID,wceyb.WECCostElementsBreakUpID ,wch.WECCostID,WCEYB.ServiceTypeID,WCEYB.WarrantyCoverageID,wecec.CostElement,weceb.Cost
 from  WECCostElementsHeader WCH inner join  WECCostElementsYearBreakUp WCEYB on WCH.WECCostElementHeaderID
 =WCEYB.WECCostElementHeaderID INNER JOIN WECCostElementsBreakUp wecEB on wecEB.WECCostElementsBreakUpID=WCEYB.WECCostElementsBreakUpID  
 left join WECCostElementsCalculation wecec on wecEB.WECCostElementID = wecec.WECCostElementID
 ) 
 select * from T
 PIVOT
 (SUM(Cost) FOR CostElement IN ('+@cols+')) as pvt'

 exec sp_executesql @query

3 个答案:

答案 0 :(得分:1)

首先需要创建要存储存储过程返回的数据的表。确保该表具有与存储过程中的结果集完全相同的列。

set PRJpath to POSIX path (choose folder)

现在,要将数据插入表中,您只需要:

pathPanel's setURL:(current application's NSURL's fileURLWithPath:PRJpath)

仅用于快速测试目的:

CREATE TABLE #TempTable (WECCostElementHeaderID int, etc. ... )

答案 1 :(得分:1)

您必须创建一个临时表,并在Insert INTO #Temporary_Table(Col1,Col2,....)语句之前放置exec sp_executesql @query。 如下所示: -

DECLARE @cols NVARCHAR(max)
    ,@query NVARCHAR(max)

SELECT @cols = stuff((
            SELECT ',[' + Ltrim(rtrim(costelement)) + ']'
            FROM WECCostElementsCalculation
            FOR XML PATH('')
            ), 1, 1, '');

CREATE TABLE #Temporary_table(Col1 datatype,Col2 datatype,Col3.....)


SELECT @query = 'with T as 
(select wch.WECCostElementHeaderID,wceyb.WECCostElementsBreakUpID ,wch.WECCostID,WCEYB.ServiceTypeID,WCEYB.WarrantyCoverageID,wecec.CostElement,weceb.Cost
 from  WECCostElementsHeader WCH inner join  WECCostElementsYearBreakUp WCEYB on WCH.WECCostElementHeaderID
 =WCEYB.WECCostElementHeaderID INNER JOIN WECCostElementsBreakUp wecEB on wecEB.WECCostElementsBreakUpID=WCEYB.WECCostElementsBreakUpID  
 left join WECCostElementsCalculation wecec on wecEB.WECCostElementID = wecec.WECCostElementID
 ) 
 select * from T
 PIVOT
 (SUM(Cost) FOR CostElement IN (' + @cols + ')) as pvt'

INSERT INTO #Temporary_table(Col1,Col2,Col3.....)
EXEC sp_executesql @query

SELECT * FROM #Temporary_table

答案 2 :(得分:1)

使用SELECT INTO:

select * 
into ##temp 
from T
PIVOT

然后在exec sp_executesql @query

之后
SELECT * FROM ##temp

如果使用临时表,您应该在主查询或其动态部分的顶部添加:

IF OBJECT_ID(N'##temp') IS NOT NULL DROP TABLE ##temp;