sql-Row to Column
DECLARE @sql_str NVARCHAR (MAX)
DECLARE @sql_col NVARCHAR (MAX)
DECLARE @tableName SYSNAME--line-to-go list
DECLARE @groupColumn SYSNAME--Group field
DECLARE @row2column SYSNAME--Row Variable column field
DECLARE @row2columnValue SYSNAME--field for row variable column values
SET @tableName = ' temp '
SET @groupColumn = ' T_userid '
SET @row2column = ' T_protitname '
SET @row2columnValue = ' T_infoanswer '
--get columns that may exist from the row data
SET @sql_str = N '
SELECT @sql_col_out = ISNULL (@sql_col_out + "," "," ") + QUOTENAME ([' [email protected]+ '])
from [' [E-mail protected]+ '] GROUP by [' [email protected]+ '] '
--print @sql_str
EXEC sp_executesql @sql_str, N ' @sql_col_out NVARCHAR (MAX) output ', @[email protected]_col output
--print @sql_col
SET @sql_str = N '
SELECT * FROM (
SELECT [' [Email protected]+ '],[' [email protected]+ '],[' [email protected]+ '] from [' [email protected]+ '] ' p PIVOT
(MAX ([' [email protected]+ ']) for [' [E-mail protected]+ '] in (' + @sql_col + ')) As Pvt
ORDER by Pvt. [' [Email protected]+ '] '
--print (@sql_str)
EXEC (@sql_str)
sql-row to column