使用 merge 语句根据不同的条件更新列
Update columns based on different criteria using merge statement
所以我使用以下合并语句进行更新并插入我的 table 之一,但是我想更新目标 table 中的另一列一个已经在声明中。我只是不确定我是否可以这样做或如何去做。我想做的是添加类似
的东西
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)));
您可以将条件从合并移动到 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)));
所以我使用以下合并语句进行更新并插入我的 table 之一,但是我想更新目标 table 中的另一列一个已经在声明中。我只是不确定我是否可以这样做或如何去做。我想做的是添加类似
的东西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)));
您可以将条件从合并移动到 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)));