【问题标题】:SQL MERGE syntaxSQL 合并语法
【发布时间】: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 ExistsIf Not Exists 逻辑。

标签: sql sql-server merge


【解决方案1】:

这是最好的。当然,您可以使用动态 SQL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-01
    • 2018-11-22
    • 2014-09-29
    • 2011-07-05
    • 2021-03-19
    • 2011-02-08
    • 2018-08-28
    • 1970-01-01
    相关资源
    最近更新 更多