sql server - Create table variable from pivot results -


is possible create table variable pivot results?

my pivot query:

select @query = 'select user_key, ' + @coldepsummary + '                 causde_tas                                  pivot                 (                 sum(usde_hsu)                 depa_key in (' + @coldepartments + ')                                ) pivot_locations                                    usde_dat >= ''' + format(@ddatefrom, 'mm.dd.yyyy') + ''' , usde_dat <= ''' + format(@ddateto, 'mm.dd.yyyy') + '''                  , user_key in (' + @users_str + ')                 group user_key' 

@coldepsummary , @coldepartments dynamically generated , looking (there around 70 columns):

@coldepsummary:

sum([120000003]),sum([120000002]),sum([140000001]),sum([120000005]), ... 

@coldepartments:

[120000003],[120000002],[140000001],[120000005], ... 

main reason why want create table variable pivot table number of columns in pivot dynamic - can vary , there lot of columns (around 70).

update

as jeremy suggested i've included into #tmp in dynamic query, looks this:

select @query = 'select user_key, ' + @coldepsummary + '                 #tmp                 causde_tas                                  pivot                 (                 sum(usde_hsu)                 depa_key in (' + @coldepartments + ')                                ) pivot_locations                                    usde_dat >= ''' + format(@ddatefrom, 'mm.dd.yyyy') + ''' , usde_dat <= ''' + format(@ddateto, 'mm.dd.yyyy') + '''                  , user_key in (' + @users_str + ')                 group user_key' 

if run query execute(@query), report saying more 200 rows affected. but, query:

select * #tmp 

is returning:

invalid object name '#tmp'.

if extract dynamic query , run manually, - #tmp created , can query it. (i extracted query select @query. i've copy-pasted selection window).

dynamic query after extraction looks this:

   select user_key, sum([120000003]),sum([120000002]),sum([140000001])    #tmp    causde_tas                  pivot    (    sum(usde_hsu)    depa_key in ([120000003],[120000002],[140000001])    ) pivot_locations                        usde_dat >= '09.19.2016' , usde_dat <= '03.18.2017'     , user_key in (100000002,100000004,100000006,100000008)    group user_key 

i don't understand why #tmp not created if run execute(@query)?


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -