代码之家  ›  专栏  ›  技术社区  ›  Ash Machine

TSQL帮助-获取行第n列中的值的方法?

  •  3
  • Ash Machine  · 技术社区  · 17 年前

    因此,对于N=6,我想要

    SELECT (Column6Value) from MyTable where MyTable.RowID = 14
    

    在SQLServer2005中实现的TSQL中有这样做的方法吗?谢谢

    5 回复  |  直到 17 年前
        1
  •  6
  •   Michael Sharek    17 年前

        2
  •  2
  •   John Rose    17 年前

    不确定您是否可以自由地重新设计表,但是如果列的顺序位置很重要,那么您的数据就没有标准化,并且对于许多常见任务,您将不得不跳过很多障碍。

    当您确实需要在一行中显示这些值时,您可以执行透视: http://geekswithblogs.net/lorint/archive/2006/08/04/87166.aspx

    编辑:我的建议有些毫无意义。Ash澄清说这是“按设计去规范化,这是一个轴心模型,其中每一行可以包含任意四种数据类型中的一种。”是的,这种设计在规范化它时可能会很麻烦。

        3
  •  2
  •   Sam Saffron James Allen    17 年前

    这项工作:

    create table test (a int, b int, c int)
    insert test values(1,2,3)
    
    declare @column_number int
    set @column_number = 2
    
    declare @query varchar(8000)
    
    select @query = COLUMN_NAME from information_Schema.Columns
    where TABLE_NAME = 'test' and ORDINAL_POSITION = @column_number
    
    set @query = 'select ' + @query + ' from test'
    
    exec(@query)
    

    但我不明白你为什么要做这样的事,你想解决什么问题?

        4
  •  0
  •   cmsjr    17 年前

    如果知道n的范围,可以使用case语句

    Select Case when @n = 1 then Column1Value when @n = 2 then  Column2Value end 
    from MyTable
    

        5
  •  0
  •   Jeff Martin    17 年前

    实现@Mike Sharek的答案。

    Declare @columnName varchar(255),
    @tablename varchar(255), @columnNumber int, @SQL nvarchar(4000)
    Set @tablename = 'MyTable'
    Set @columnNumber = 6
    
    
    Select @columnName = Column_Name from Information_SChema.columns
    where Ordinal_position = @columnNumber and Table_Name = @tablename
    
    Set @SQL  = 'select ' + @columnName + ' from ' + @tableName + ' where RowID=14'
    Exec sp_Executesql @SQL