如何使用动态SQL查询结果创建临时表

时间:2017-11-16 11:59:07

标签: sql sql-server stored-procedures

我有这个存储过程:

Declare @MarketID AS NVARCHAR(MAX) = '1.136529848';
Declare @UserID AS NVARCHAR(MAX) = '6a309d84-d1c6-434d-b9df-4f96a74da912';

DECLARE @colsSelect AS NVARCHAR(MAX);
DECLARE @colsTemp AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT
    @colsSelect = STUFF((SELECT distinct ',' +
                    '''''' + ' as ' + QUOTENAME(name) 
                         FROM RunnersInfoes  AS t 
                         WHERE marketID = @MarketID 
                         FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 1, '');

PRINT @colsSelect

SET @query= ';WITH cte AS
             (
                  SELECT
                      id, ParentId, 0 AS Level, Share, AccountTypeName, FirstName
                  FROM
                      dbo.View_UserProfile 
                  WHERE
                      View_UserProfile.id = ' + '''' + @UserID + '''' +'
                  UNION ALL
                  SELECT
                      t.id, t.ParentId, Level + 1 AS Level, t.Share, t.AccountTypeName, t.FirstName
                  FROM
                      View_UserProfile t  
                  INNER JOIN
                      cte ON t.ParentId = cte.id
             )
             SELECT 
                 ID, AccountTypeName AS Type, FirstName AS Name, ' + @colsSelect + '      
             FROM cte AS t'

EXECUTE (@query)

并且它产生了这个结果:

result

我想为后续结果创建临时表或变量类型表,请记住此结果的列是动态呈现的。有时结果会返回更多列,有时会返回更少但前三列保持相同的每个结果。所以请帮助在存储过程中创建动态表。

3 个答案:

答案 0 :(得分:1)

你可以这样做:

SELECT ID
,      AccountTypeName AS Type
,      FirstName AS Name
,      ' + @colsSelect + ' 
INTO   ##TEMPTABLE     
FROM   cte AS t

由于您动态执行此操作,因此无法使用#TEMPTABLE,因为本地临时表将仅存在于定义它的查询范围内。使用##创建一个全局临时表,可以在动态查询范围之外访问。

答案 1 :(得分:0)

请根据您的用例使用SELECT - INTO子句,如下所示

SELECT * INTO #temptable FROM cte

答案 2 :(得分:0)

要创建由动态查询填充的临时表,请使用此示例中的全局临时表 要使declare @query varchar(1000) = 'select 1 as ID, ''test'' as Column_1 into ##mytable' exec (@Query) select * from ##mytable drop table ##mytable 语句起作用,您需要确保select中的每一列都有一个名称。

security.sandbox.content.level

完成后不要忘记放下临时表。