将 WHEN NOT MATCHED 输出合并到另一个表中

问题描述 投票:0回答:1

我想将不匹配的输出插入到两个表中。当我尝试插入存储过程的输出时,它会将所有更新的值也添加到新表中,而不仅仅是“表”中没有匹配的值

尝试了好几种方法都没用

ALTER PROCEDURE [dbo].[identify]
AS
BEGIN
    SET NOCOUNT ON;

    MERGE INTO [test].[dbo].[warehouse] AS dim
    USING [test].[dbo].[staging] AS stg
        ON dim.[first_name] = stg.first_name
    WHEN MATCHED THEN
        UPDATE SET
            dim.[first_name] = stg.first_name,
            dim.last_name = stg.last_name,
            dim.created_date = stg.created_date,
            dim.modified_date = stg.modified_date,
            dim.gender = stg.gender
    WHEN NOT MATCHED THEN
        INSERT(first_name, last_name, created_date, modified_date, gender)
        VALUES(first_name, last_name,created_date, modified_date,gender)
    OUTPUT Inserted.first_name, Inserted.last_name INTO test (first_name,last_name);

END
sql sql-server stored-procedures data-warehouse
1个回答
0
投票

将所有更改捕获到临时表中 - 包括来自

Inserted
Deleted
的不可空列,例如
id
。然后从临时表插入实际表,其中 Inserted
id
不为 null,Deleted
id
为 null - 因为这是
NOT MATCHED
的定义。

...
OUTPUT Inserted.id, Inserted.first_name, Inserted.last_name, Deleted.id INTO #test (new_id, new_first_name, new_last_name, old_id);

INSERT INTO test (first_name, last_name)
SELECT new_first_name, new_last_name
FROM #test
WHERE new_id IS NOT NULL AND old_id IS NULL;

DROP TABLE #test;
© www.soinside.com 2019 - 2024. All rights reserved.