我有一个只输出一行数据的查询。我想将该行转换为列,将列转换为行。
我的原始查询
------------------------
ID Name Desc
------------------------
1 Nisha Some desc
我需要什么
--------------------------
FieldName FieldValue
--------------------------
ID 1
Name Nisha
Description Some Desc
答案 0 :(得分:0)
declare @colNum int, @i int = 1, @a nvarchar(4000)
select @colNum=count(COLUMN_NAME) from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTable'
set @a = '
declare @tempTable table
(
slno int
,field nvarchar(100)
,value nvarchar(100)
)
insert into @tempTable (slno,field)
select ROW_NUMBER() over (order by ordinal_position asc),COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ''YourTable''
declare @p nvarchar(100)
'
declare @colname nvarchar(100)
while @i<=@colNum
begin
select @colname =a.COLUMN_NAME from (select COLUMN_NAME,ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTable'
)as a
where a.ORDINAL_POSITION = @i
set @a = @a + '
select @p='+@colname+' from YourTable
update @tempTable set
value = @p
where slno = '+CONVERT(nvarchar(5), @i)
+'
'
set @i=@i+1
end
set @a = @a + ' select * from @tempTable'
declare @tempTable table
(
slno int
,field nvarchar(100)
,value nvarchar(100)
)
insert into @tempTable exec (@a)
select * from YourTable
select * from @tempTable