是否有更简洁的方式来编写此查询?
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.*
答案 0 :(得分:1)
这很好。当然,您可以使用动态SQL。