您应该可以为此使用UNPIVOT:
这是一个静态数据透视表,您可以在其中对列的值进行硬编码:
create table t1
(
col1 varchar(5),
col2 varchar(5),
col3 varchar(5),
col4 varchar(5)
)
insert into t1 values ('xxxx', 'yyyy', 'zzzz', 'aaaa')
select question, answer
FROM t1
unpivot
(
answer
for question in (col1, col2, col3, col4)
) u
drop table t1
这是一个带有演示的SQL Fiddle 。
但您也可以使用 Dynamic Unpivot:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
select @cols = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id('t1') and
C.name like 'Col%'
for xml path('')), 1, 1, '')
set @query = 'SELECT question, answer
from t1
unpivot
(
answer
for question in (' + @cols + ')
) p '
execute(@query)