INSERT INTO temp table from unknown number and name of columns (from dynamic PIVOT query)

孤者浪人 提交于 2019-12-13 03:36:14

问题


I have a dynamic query as shown below. The @ColumnNames param has multiple columns this pivot is using. @ID and @Apartment_ID come from insert parameters.

SET @DynamicSQL = 'select id, name, address, phone, remarks, ' + **@ColumnNames** + ' 
                   from  (select b.id, name, criteria_id, impact_value, remarks  
                          from dbo.User u
                          inner join dbo.ID b on b.id = u.id
                          where b.Instance_ID = '+ **@Id**  + 
                           'and ownerID in (select * from fnSplitString(''' +   **@Apartment_ID**  + + ''',' + ''','''       + '))'              
              + ') as t  
              pivot (max(impact_value) for criteria_id in (' + **@ColumnNames**+')
              ) pivoted '

Exec sp_executesql @DynamicSQL 

will be get a result as shown in the screenshot. The columns (91, 92,..) are not fixed that get from @ColumnNames:

I want to insert this dynamic result set into temp table to make sorts function.

Declare @SQLstrs nvarchar(max)

IF OBJECT_ID('tempdb..#tempResult') IS NOT NULL
    DROP TABLE #tempResult  

CREATE TABLE #tempResult 
(  
     id int,
     name nvarchar(max),
     address nvarchar(max),
     phone nvarchar(max),
     Remarks nvarchar(max),
     **@ColumnNames**
)

--EXEC (@Alter_sql);

SET @SQLstrs = 'Insert into #tempResult ' + @DynamicSQL 

EXEC @SQLstrs

Since temp table need to include the fixed columns, how can I set up the dynamic columns that can't know how many columns will be insert ?


回答1:


try to use select into

 SET @SQLstrs = 'select * into #tempResult from(' + @DynamicSQL  +') as _temp'


来源:https://stackoverflow.com/questions/45792367/insert-into-temp-table-from-unknown-number-and-name-of-columns-from-dynamic-piv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!