Create temp table with column names from another t

2019-08-15 06:18发布

问题:

Is it possible to create a temp table with columns named with data from a single column in another table for example -

singleColumn
-data1
-data2
-data3
-data4

then from this create a temp table like -

data1 | data2 | data3 | data4

edit:

I have a user that can have 0 to whatever demographics from the demographics table. A join will return several rows for a user. I need this data joined on 1 row so I can store this data in CSV file.

回答1:

declare @dynamicSql varchar(1000)
set @dynamicSql = 'create table #yourTempTable ('

select @dynamicSql += yourDataCol + ' nvarchar(100) not null, '
from TestTempTables

set @dynamicSql = LEFT(@dynamicSql, len(@dynamicSql) - 1) + ')'

exec(@dynamicSql)


回答2:

Don't think its possible to return data the way I would like so ended up doing doing it with 2 DataTables.