合并条件(SQL 服务器)
Merging with conditions (SQL Server)
我有两个 tables,TABLE A 和 TABLE B,格式相同。我是 运行 使用 Table B 作为源的合并语句
TYPE ITEM QTY1 QTY2 QTY3
A AAA 100 200 300
A BBB 150 250 310
B CCC 101 123 131
C DDD 102 55 12
事实是,我只想在记录已存在于目标 table 中时更新特定列。这是我想做的,但我似乎无法让它发挥作用。我只是想知道,是否可以使用 MERGE 语句?
MERGE TABLE A
USING (SELECT * FROM TABLE B) B
ON B.TYPE = A.TYPE AND B.ITEM = A.ITEM
WHEN NOT MATCHED THEN
INSERT (TYPE, ITEM, QTY1, QTY2, QTY3) VALUES (B.TYPE, B.ITEM, B.QTY1, B.QTY2, B.QTY3)
WHEN MATCHED THEN
CASE
WHEN 'A' : UPDATE SET A.QTY1 = B.QTY1, A.QTY2 = B.QTY2, A.QTY3 = B.QTY3
WHEN 'B' : UPDATE SET A.QTY2 = B.QTY2 , A.QTY3 = B.QTY3
WHEN 'C' : UPDATE SET A.QTY3 = B.QTY3
END;
您可以在 WHEN MATCHED
子句中添加一个条件,并且有多个条件:
MERGE [TABLE A]
USING (SELECT * FROM [TABLE B]) B
ON B.TYPE = A.TYPE AND B.ITEM = A.ITEM
WHEN NOT MATCHED THEN
INSERT (TYPE, ITEM, QTY1, QTY2, QTY3) VALUES (B.TYPE, B.ITEM, B.QTY1, B.QTY2, B.QTY3)
WHEN MATCHED AND A.TYPE = 'A' THEN
UPDATE SET A.QTY1 = B.QTY1, A.QTY2 = B.QTY2, A.QTY3 = B.QTY3
WHEN MATCHED AND A.TYPE = 'B' THEN
UPDATE SET A.QTY2 = B.QTY2 , A.QTY3 = B.QTY3
WHEN MATCHED AND A.TYPE = 'C' THEN
UPDATE SET A.QTY3 = B.QTY3;
有关详细信息,请参阅 the documentation。
我有两个 tables,TABLE A 和 TABLE B,格式相同。我是 运行 使用 Table B 作为源的合并语句
TYPE ITEM QTY1 QTY2 QTY3
A AAA 100 200 300
A BBB 150 250 310
B CCC 101 123 131
C DDD 102 55 12
事实是,我只想在记录已存在于目标 table 中时更新特定列。这是我想做的,但我似乎无法让它发挥作用。我只是想知道,是否可以使用 MERGE 语句?
MERGE TABLE A
USING (SELECT * FROM TABLE B) B
ON B.TYPE = A.TYPE AND B.ITEM = A.ITEM
WHEN NOT MATCHED THEN
INSERT (TYPE, ITEM, QTY1, QTY2, QTY3) VALUES (B.TYPE, B.ITEM, B.QTY1, B.QTY2, B.QTY3)
WHEN MATCHED THEN
CASE
WHEN 'A' : UPDATE SET A.QTY1 = B.QTY1, A.QTY2 = B.QTY2, A.QTY3 = B.QTY3
WHEN 'B' : UPDATE SET A.QTY2 = B.QTY2 , A.QTY3 = B.QTY3
WHEN 'C' : UPDATE SET A.QTY3 = B.QTY3
END;
您可以在 WHEN MATCHED
子句中添加一个条件,并且有多个条件:
MERGE [TABLE A]
USING (SELECT * FROM [TABLE B]) B
ON B.TYPE = A.TYPE AND B.ITEM = A.ITEM
WHEN NOT MATCHED THEN
INSERT (TYPE, ITEM, QTY1, QTY2, QTY3) VALUES (B.TYPE, B.ITEM, B.QTY1, B.QTY2, B.QTY3)
WHEN MATCHED AND A.TYPE = 'A' THEN
UPDATE SET A.QTY1 = B.QTY1, A.QTY2 = B.QTY2, A.QTY3 = B.QTY3
WHEN MATCHED AND A.TYPE = 'B' THEN
UPDATE SET A.QTY2 = B.QTY2 , A.QTY3 = B.QTY3
WHEN MATCHED AND A.TYPE = 'C' THEN
UPDATE SET A.QTY3 = B.QTY3;
有关详细信息,请参阅 the documentation。