0

1 行のデータのみを出力するクエリがあります。その行を列に、列を行に変換したい。

私の元のクエリ

------------------------
ID     Name     Desc
------------------------
1     Nisha     Some desc

私が必要なもの

--------------------------
FieldName     FieldValue
--------------------------
ID            1
Name          Nisha
Description   Some Desc
4

1 に答える 1

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
于 2013-10-23T06:00:24.287 に答える