【发布时间】:2015-07-06 21:40:24
【问题描述】:
有没有更简洁的方法来编写这个查询?
MERGE INTO TARGET_TABLE AS t
USING SOURCE_TABLE AS s
ON t.LOCAL_ID = s.LOCAL_ID
WHEN MATCHED
AND (
t.[col1] <> s.[col1]
OR t.[col2] <> s.[col2]
OR t.[col5] <> s.[col5]
OR t.[col6] <> s.[col6]
OR t.[col8] <> s.[col8]
OR t.[col13] <> s.[col13]
OR t.[col15] <> s.[col15]
)
THEN
UPDATE
SET [col1] = s.[col1]
,[col2] = s.[col2]
,[col5] = s.[col5]
,[col6] = s.[col6]
,[col8] = s.[col8]
,[col13] = s.[col13]
,[col15] = s.[col15]
WHEN NOT MATCHED BY TARGET
THEN
INSERT (
[LOCAL_ID]
,[col1]
,[col2]
,[col5]
,[col6]
,[col8]
,[col13]
,[col15]
)
VALUES (
,s.[LOCAL_ID]
,[col1]
,[col2]
,[col5]
,[col6]
,[col8]
,[col13]
,[col15]
)
WHEN NOT MATCHED BY SOURCE
THEN
DELETE
OUTPUT GetDate()
,s.LOCAL_ID
,$ACTION
,deleted.[col1] col1
,deleted.[col2] col2
,deleted.[col5] col5
,deleted.[col6] col6
,deleted.[col8] col8
,deleted.[col13] col13
,deleted.[col15] col15
,inserted.[col1] NEW_col1
,inserted.[col2] NEW_col2
,inserted.[col5] NEW_col5
,inserted.[col6] NEW_col6
,inserted.[col8] NEW_col8
,inserted.[col13] NEW_col13
,inserted.[col15] NEW_col15
INTO [AUDIT];
这些列是两个表的子集,所以我认为通配符对我没有多大帮助。
但是,两个表的字段名称相同。 AUDIT 可以包含 deleted.* 和 inserted.* 在专门采摘列内
【问题讨论】:
-
我不明白它有什么不“干净”的地方。它根据一组规则清楚地指定了源、目标以及您要插入/更新/删除的内容。在我看来很干净。如果您不喜欢
MERGE语句,您可以随时使用单独的 Insert、Update 和 Delete 语句,像过去一样使用If Exists和If Not Exists逻辑。
标签: sql sql-server merge