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


i have dynamic query shown below. @columnnames param has multiple columns pivot using. @id , @apartment_id come insert parameters.

set @dynamicsql = 'select id, name, address, phone, remarks, ' + **@columnnames** + '                      (select b.id, name, criteria_id, impact_value, remarks                             dbo.user u                           inner join dbo.id b on b.id = u.id                           b.instance_id = '+ **@id**  +                             'and ownerid in (select * fnsplitstring(''' +   **@apartment_id**  + + ''',' + ''','''       + '))'                             + ') t                 pivot (max(impact_value) criteria_id in (' + **@columnnames**+')               ) pivoted '  exec sp_executesql @dynamicsql  

will result shown in screenshot. columns (91, 92,..) not fixed @columnnames:

image description here

i want insert dynamic result set temp table make sorts function.

declare @sqlstrs nvarchar(max)  if object_id('tempdb..#tempresult') 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 #tempresult ' + @dynamicsql   exec @sqlstrs 

since temp table need include fixed columns, how can set dynamic columns can't know how many columns insert ?

try use select into

 set @sqlstrs = 'select * #tempresult from(' + @dynamicsql  +') _temp' 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -