有一张表,其中多个列的值需要更正。然后有一个表,其中包含所有需要更正的值。
有没有简单的方法在MERGE语句中使用CROSS APPLY?
以我目前的知识,我需要为column1,column2等运行以下代码。
MERGE INTO target_table AS t
USING source_table AS s
ON t.key_column = s.key_column
AND 'column_1' = s.correction_column
WHEN MATCHED THEN
UPDATE SET t.column_1 = s.correction_value;
编辑: 这些是目标,来源和预期结果的示例。
目标:
## | uid | col_1 | col_2 | col_3 | col_4 | col_5
----------------------------------------------------
## 1 | 1 | a | a | a | a | a
## 2 | 2 | a | a | a | a | a
## 3 | 3 | a | a | a | a | a
## 4 | 4 | a | a | a | a | a
## 5 | 5 | a | a | a | a | a
## 6 | 6 | a | a | a | a | a
来源:
## | uid | col | value
----------------------------
## 1 | 1 | col_1 | B
## 2 | 1 | col_2 | C
## 3 | 4 | col_3 | D
## 4 | 4 | col_4 | E
## 5 | 5 | col_3 | F
预期结果:
## | uid | col_1 | col_2 | col_3 | col_4 | col_5
----------------------------------------------------
## 1 | 1 | B | C | a | a | a
## 2 | 2 | a | a | a | a | a
## 3 | 3 | a | a | a | a | a
## 4 | 4 | a | a | D | E | a
## 5 | 5 | a | a | F | a | a
## 6 | 6 | a | a | a | a | a
答案 0 :(得分:0)
您可以在括号中添加查询以创建派生表
示例
MERGE INTO target_table AS t
USING (select * from source_table a cross apply (select top 1 * from other_table b where b.id = a.id order by some_date desc) b2) AS s
ON t.key_column = s.key_column
AND 'column_1' = s.correction_column
WHEN MATCHED THEN
UPDATE SET t.column_1 = s.correction_value;