0

因此,我正在使用以下合并语句在我的一个表中进行更新和插入,但是除了语句中已经存在的列之外,我还想更新 Target 表中的另一列。我只是不确定我是否可以做到这一点或如何去做。我想要做的是添加类似

when MATCHED and Source.EventType='Change' Then UPDATE SET Target.DEDCAMT_1 = Source.EmpDedAmt

我可以在同一个 Merge 语句中这样做吗?

    MERGE dbo.BENTBL as Target
    using dbo.BenPaycdUpdate as Source
    ON Source.EmpID = Target.EMPLOYID AND Source.Paycode = Target.DEDUCTON
    WHEN MATCHED AND source.EventType='Stop'
    THEN UPDATE
    SET INACTIVE = '1',
    Target.DEDENDDT = Source.AsOfDate
    WHEN NOT MATCHED BY Target
    AND Source.PayCode <> 'FSAH' 
    THEN INSERT (EMPLOYID, DEDUCTON, INACTIVE, DEDBEGDT, DEDCAMNT_1)
    VALUES (Source.EmpID, Source.Paycode,'0', Source.AsofDate,
    CAST(REPLACE  (REPLACE(ISNULL(source.EmpDed,0),',',''),'$','') AS numeric(19,5)));
4

1 回答 1

0

您可以将条件从合并移动到 case 表达式,如下所示:

MERGE dbo.BENTBL as Target
using dbo.BenPaycdUpdate as Source
ON Source.EmpID = Target.EMPLOYID AND Source.Paycode = Target.DEDUCTON
WHEN MATCHED THEN 
UPDATE
SET INACTIVE = CASE WHEN source.EventType = 'Stop' THEN '1' ELSE INACTIVE END,
    Target.DEDCAMT_1 = CASE WHEN source.EventType = 'Change' THEN Source.EmpDedAmt ELSE Target.DEDCAMT_1 END,
    Target.DEDENDDT = Source.AsOfDate
WHEN NOT MATCHED BY Target AND Source.PayCode <> 'FSAH' THEN 
INSERT (EMPLOYID, DEDUCTON, INACTIVE, DEDBEGDT, DEDCAMNT_1)
VALUES (Source.EmpID, Source.Paycode,'0', Source.AsofDate,
CAST(REPLACE  (REPLACE(ISNULL(source.EmpDed,0),',',''),'$','') AS numeric(19,5)));
于 2018-12-19T05:43:06.713 回答