简体   繁体   中英

SQL Server 2008 R2 dynamic column name usage

I have a table, let's say:

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)

I have a procedure that after heavy processing it comes up with a date and a number from 1 to 9.

If 1 is picked for that date I want to return salary1, if 2 is picked I want to return salary2 etc.

I want to avoid using 8 if else clauses:

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

blah 

blah

I would like to know if there is an elegant way to get the corect salaryX field depending on the procedure number outcome.

Thanx guys!!

No need for dynamic code

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
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM