如何在高效查询中快速批量更新值?

How do I mass update values quickly in an efficient query?

我有 3 个包含相同列的表,Report Year

我想更新任何没有描述的报告年份。例如,查看下面的示例数据,您可以看到有些年份没有任何后缀,例如 6+6 或 7+5。

那些没有后缀且只是独立的年份(即 2020、2021 等),我想为它们添加一个后缀“LTP”,这样它们就会变成“2020 LTP”, “2021 LTP”等... 独立年份但以字符开头的年份,例如 BP19,不应更新!

伪查询:

UPDATE table1, table2, table3
SET 
    [Report Year] = [Report Year].append(' LTP')
WHERE
    [Report Year].count < 5;

我在我的伪代码中使用 count 作为条件,因为这是我能想到的使查询足够智能以识别哪一年有后缀和什么没有后缀的唯一方法,以便它可以附加后缀 'LTP' 相应地。如果有更好的方法,我很乐意看到:)

报告年份列中的示例值:

表 1(将报告年份作为主键,因此只有 Unique/Distinct 个值):

Report Year
2020 5+7
BP19
2020
2020 6+6
2020 7+5
2021
2022 4+8
2022 
2022

表 2:

Report Year
2020
2020
2020
2020 6+6
2021
2022 4+8
2022 BP
2022
2020 6+6
2020
2020 6+6
2021
2022 4+8
2022
2022 
2022

表 3:

Report Year
2020 5+7
2020 5+7
2020
2020
BP19
2020
2020 6+6
2020 7+5
2021
2022 4+8
2022 
2022
2020 6+6
2020 6+6
2020 7+5
2021
2022 4+8
2022 
2022 

您的 pseudo-code 翻译为四个 update 语句:

update table1
set [Report Year] = concat([Report Year], ' LTP')
where len([Report Year]) = 4;

update table2
set [Report Year] = concat([Report Year], ' LTP')
where len([Report Year]) = 4;

update table3 ...

update table4 ...

逻辑是只识别报告年份为4个字符的记录,然后追加字符串“LTP”。 4 个 table 中的每一个都独立于其他,因此 运行 4 个查询是正确的方法。


如果要过滤仅包含数字而不是 4 个字符的报告年份,请使用 not like 和模式匹配:

where [Report Year] NOT LIKE '%[^0-9]%'

此短语为:报告年份不应包含任何 non-digit 个字符。

要确保 [Report Year] 列仅包含 4 位数字年份而没有后缀,您可以测试以确保 4 个字符以 1 或 2 开头,其余 3 个字符为 [0-9]。像这样

update table1
set [Report Year] = concat([Report Year], ' LTP')
where [Report Year] like '[1-2][0-9][0-9][0-9]';

update table2
set [Report Year] = concat([Report Year], ' LTP')
where [Report Year] like '[1-2][0-9][0-9][0-9]';

update table3 ...

update table4 ...