【问题标题】:How can show one Row in rows in which each row contain column name and the other contain the value?如何在每行包含列名而另一行包含值的行中显示一行?
【发布时间】:2010-09-27 09:41:35
【问题描述】:

我有一个包含大约 60 列的表,如果我在查询分析器中编写一个选择查询以获取一行,它会显示它,我必须滚动以显示数据..
如何获得显示为 60 行的一行,每行包含 2 列,一列用于列名,另一列用于值
例如Select * from table where id = 1 默认显示为

ID Col1  Col2  Col3 Col4 Col5 ...... Col60  
1  v1    v2    v3   v4   v5   ...... v60

我希望它显示为

ID    1  
Col1  v1  
Col2  v2  
Col3  v3
...  
Col60 v60

【问题讨论】:

    标签: sql sql-server-2005 select


    【解决方案1】:

    下面的存储过程做你需要的

    CREATE PROCEDURE [dbo].[Rotat]
        -- Add the parameters for the stored procedure here
         @Where nvarchar(max),
         @tableName nvarchar(max)
    AS
    BEGIN
    
    Declare @SqlQuery nvarchar(max),@ColumnName nvarchar(255)
    DECLARE @TempTable TABLE 
    ( 
          ID int IDENTITY(1,1) , 
          ColumnName nvarchar(255), 
          ColumnValue ntext 
    )
    
    
    INSERT INTO @TempTable (ColumnName)
        SELECT      column_name
        FROM information_schema.columns
        WHERE table_name = @tableName 
    
    Declare @index int
    Set @index = 1;  
    
    Declare @Count int
    Select @Count = Count(ID) from @TempTable
    declare @columnValue  nvarchar(255)
    declare @paraDef nvarchar(max)
    declare @string nvarchar(max)
    
    WHILE @index <= @Count 
    BEGIN
        Select @ColumnName = ColumnName from @TempTable where id = @index
        set @string ='select @ret= cast('+ @ColumnName + ' AS nvarchar(255) )  
            from '+@tableName+' WHERE ' + @Where
    
        set  @paraDef=N'@ret nvarchar(255) output'
    
        EXECUTE sp_executesql @string, @paraDef,@ret=@ColumnValue  output
    
        UPDATE  @TempTable 
        SET     ColumnValue = @columnValue
        WHERE   ID =@index
    
        Set @index = @index + 1
    END
    
    Select * from @TempTable
    
    END
    

    只需将其称为传递表名称和将返回一行的条件,例如

    EXEC    [dbo].[Rotat]
            @Where = 'UserID = 123456',
            @tableName = 'Users'
    

    【讨论】:

      【解决方案2】:

      如果您想要一种非常快速的技术来查看转置的数据(正如您的问题所暗示的那样),请尝试将结果网格中的输出复制并粘贴到 Excel 中,然后复制 Excel 数据并使用选择性粘贴来转置输出.

      【讨论】:

      • 我希望它公开,我可以将它用于任何表
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多