SQL 将键映射到值的函数
SQL function to map key to value
我正在尝试创建一个 SQL 函数来将键映射到值。目标是将包含 Windows 时区名称的 table 迁移到 iana 时区名称,类似这样
Insert Into IanaTable (IanaTimezone)
Select TzConvert(WindowsTimeZone)
From WindowsTzTable
我看到大约有 50 个 windows 时区并且愿意为这 50 个项目编写手动转换。我看过其他一些答案,但我希望不要写一个很大的 IF/ELSE 函数
SQL function to manipulate values
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 表示他们更喜欢函数,因为相同的值将分配给多个列,因此我反对使用横向连接来为表达式添加别名。这更好,因为即使 copy-pasting 函数的名称仍然是 WET 并且容易出错。这里:
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
我正在尝试创建一个 SQL 函数来将键映射到值。目标是将包含 Windows 时区名称的 table 迁移到 iana 时区名称,类似这样
Insert Into IanaTable (IanaTimezone)
Select TzConvert(WindowsTimeZone)
From WindowsTzTable
我看到大约有 50 个 windows 时区并且愿意为这 50 个项目编写手动转换。我看过其他一些答案,但我希望不要写一个很大的 IF/ELSE 函数
SQL function to manipulate values
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 表示他们更喜欢函数,因为相同的值将分配给多个列,因此我反对使用横向连接来为表达式添加别名。这更好,因为即使 copy-pasting 函数的名称仍然是 WET 并且容易出错。这里:
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