SQL Server 2008 R2动态列名用法

时间:2016-12-15 07:41:21

标签: sql sql-server select sql-server-2008-r2

我有一张桌子,让我们说:

CREATE TABLE dbo.test
(dummyid numeric(10,0) null,
    on_date datetime      null,
    salary1 numeric(10,2) null,
    salary2 numeric(10,2) null,
    salary3 numeric(10,2) null,
    salary4 numeric(10,2) null,
    salary5 numeric(10,2) null,
    salary6 numeric(10,2) null,
    salary7 numeric(10,2) null,
    salary8 numeric(10,2) null,
    salary9 numeric(10,2) null)

我有一个程序,经过繁重的处理,它会提供一个日期和1到9的数字。

如果在该日期选择1,我想返回salary1,如果选择2,我想返回salary2等。

我想避免使用8 if else子句:

IF @number = 1
    BEGIN
    SELECT @salary = salary1
    FROM test
       WHERE on_date = @on_date

blah 

blah

我想知道是否有一种优雅的方法来获取corect salaryX字段,具体取决于程序编号结果。

Thanx家伙!!

1 个答案:

答案 0 :(得分:2)

无需动态代码

select      case @numebr
                when 1 then salary1   
                when 2 then salary2
                when 3 then salary3
                when 4 then salary4
                when 5 then salary5
                when 6 then salary6
                when 7 then salary7
                when 8 then salary8
                when 9 then salary9
            end                         as salary

from        dbo.test

where       on_date = @date
;