Any equivalent to Excel CHOOSE function?

I would be surprised if this was not asked before, but I could not find anything. Excel has a function

CHOOSE(n, x_1, x_2, x_3, ...)

which returns x_n for the given value of n.

Is there anything similar in SQL (standard or specific for MS) supported by SQL Server 2008? I know that this really should be implemented using a lookup table in the database, but for what I am doing, I cannot add new tables to the database.

I could create a temporary table and populate it from an SQL script or use

CASE n WHEN 1 THEN x_1 WHEN 2 THEN x_2 WHEN 3 THEN x_3 ... END

but is there anything less cumbersome?

+4
source share
2 answers

Unfortunately, no, it doesn't seem to be real in your version.

CHOOSE -Function SQL Server 2012 , Excel-.

+5

", , , ". , , , - :

select
    ...,
    l.v
from <your table> as t
    left outer join (values
        (1, x_1), (2, x_2), (3, x_3)
    ) as l(n, v) on l.n = t.n

, choose():

create function dbo.f_Choose5(
    @index int,
    @value1 sql_variant,
    @value2 sql_variant,
    @value3 sql_variant,
    @value4 sql_variant,
    @value5 sql_variant
)
returns sql_variant
as
begin
    return (
        case @index
            when 1 then @value1
            when 2 then @value2
            when 3 then @value3
            when 4 then @value4
            when 5 then @value5
        end
    )
end

select dbo.f_Choose5(3, 1, 2 ,3, 4, 5)
select dbo.f_Choose5(3, 1, 2 ,3, default, default)

, SQL Server .

+2

Source: https://habr.com/ru/post/1584463/


All Articles