INSERT INTO temp table from unknown number and nam

2019-08-20 10:19发布

问题:

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'