sql server - TSQL transform row values into one column table -
source table
col1 |col2 |col3 |col4 | col5 ---------------------------------- hi | | | | test
destination table
rowvalues| ---------- hi test
i using dynamic sql. ?
this code , change table name , id in clause suits you
declare @sql nvarchar(max), @tablename nvarchar(100), @where nvarchar(max) set @tablename = 'stockitems' set @where= ' id = 2' select @sql ='select ' select @sql = @sql+ + ' '''+ [name] +' = ''+ cast(' + [name] + ' nvarchar(10)) '+[name]+', ' sys.columns object_name (object_id) = @tablename set @sql = stuff(@sql, len(@sql), 1, '') + ' '+@tablename+ @where print @sql set @sql = replace(@sql,', from',' from') set @sql = @sql + ' ' print @sql exec(@sql)
now need create new table has 1 column hold holds each value row
thanks @mahmoud-gamal solution should below
declare @cols nvarchar(max) select @cols = stuff((select distinct ',' + quotename(column_name) information_schema.columns table_name = 'vehicles' xml path(''), type ).value('.', 'nvarchar(max)') , 1, 1, ''); declare @statement nvarchar(max) set @statement =' select columnname, value vehicles unpivot ( value columnname in ( '+@cols+' ) ) a' execute(@statement)
please change "vehicle" table name table on database has columns different types (datetime, int , nvarchar) , below error shown ? the type of column "description" conflicts type of other columns specified in unpivot list.
use unpivot
table operator:
select col rowvalues table1 t unpivot ( col value in([col1], [col2], [col3], [col4], [col5]) ) u;
this give you:
| rowvalues | |-----------| | hi | | | | | | | | test |
update:
in case don't know names of columns, , want dynamically, have using dynamic sql.
but problem how columns names?
you can columns names information_schema.columns
, concatenate them in 1 sql, replace columns' names in unpivot
string, , execute statement dynamically this:
declare @cols nvarchar(max); declare @query nvarchar(max); select @cols = stuff((select distinct ',' + quotename(column_name) information_schema.columns table_name = 'table1' xml path(''), type ).value('.', 'nvarchar(max)') , 1, 1, ''); select @query = ' select col rowvalues table1 t unpivot ( val col in ( ' + @cols + ' ) ) u;'; execute(@query);
Comments
Post a Comment