如何将列转换为行sql

时间:2014-01-22 14:48:06

标签: sql sql-server

我需要在MS Sql中将列转换为行。所以我尝试下面的代码

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('tbl_login_settings') 

         for xml path('')), 1, 1, '')

set @query 
  = 'select  value
     from tbl_login_settings
     unpivot
     (
        value
        for year in ('+ @colsunpivot +')
     ) lab_name'

exec(@query)

它工作正常,但问题是它将所有列(所有行值)转换为行。

我需要特定的列(行值)到行

e.g

sno/ name/ visible// column name
1  / sam / show
2  / ram / hide // i need to convert this rows like below
3  / mick / show

values// column name
2
ram
hide

1 个答案:

答案 0 :(得分:0)

试试这个

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('tbl_login_settings') 

         for xml path('')), 1, 1, '')

set @query 
  = 'select  value
     from tbl_login_settings where sno = 2
     unpivot
     (
        value
        for year in ('+ @colsunpivot +')
     ) lab_name'

exec(@query)