代码之家  ›  专栏  ›  技术社区  ›  qkhanhpro

将键映射到值的SQL函数

  •  0
  • qkhanhpro  · 技术社区  · 2 年前

    我试图创建一个SQL函数来将键映射到值。目标是将包含Windows时区名称的表迁移到iana时区名称,类似这样

    Insert Into IanaTable (IanaTimezone)
    Select TzConvert(WindowsTimeZone)
    From WindowsTzTable
    

    我看到大约有50个windows时区,并且愿意为这50个项目编写手动转换。我已经看过了一些其他的答案,但我不希望写一个非常大的IF/ELSE函数

    SQL function to manipulate values

    1 回复  |  直到 2 年前
        1
  •  1
  •   George Menoutis    2 年前

    IF 用于流量控制。对于表达式,只需使用 CASE :

    Insert Into IanaTable (IanaTimezone)
        Select 
            case
                when CONDITION1 then RESULT1
                when CONDITION2 then RESULT2
                ......
                when CONDITION100 the RESULT100
            end as IanaTimezone         
        From WindowsTzTable
    

    编辑:由于OP表示他们更喜欢一个函数,因为相同的值将分配给多个列,所以我反对使用横向连接来别名表达式。这是更好的,因为即使是复制粘贴函数名也是湿的,而且容易出错。在这里:

    Insert Into IanaTable (...)
        Select 
             q1.IanaTimezone as column1
            ,q1.IanaTimezone as column2
            ,q1.IanaTimezone as column3
            ,othervalue      as othercolumn
            ......
        From 
            WindowsTzTable
            cross apply
            (
                Select 
                case
                    when CONDITION1 then RESULT1
                    when CONDITION2 then RESULT2
                    ......
                    when CONDITION100 the RESULT100
                end as IanaTimezone 
            ) as q1