小编典典

在这种情况下如何使用T-SQL MERGE?

sql

我是T-SQL命令的新手,MERGE所以我在SQL逻辑中找到了一个可以使用它并想要对其进行测试的地方,但无法弄清楚我应该如何使用它:

IF (EXISTS (SELECT 1 FROM commissions_history WHERE request = @requestID))
    UPDATE commissions_history
    SET amount = @amount
    WHERE request = @requestID
ELSE
    INSERT INTO commissions_history (amount) VALUES @amount)

请提出正确的用法。谢谢!


阅读 165

收藏
2021-03-23

共1个答案

小编典典

您在帮助中了吗?这是一个简单的例子:

MERGE dbo.commissions_history AS target
USING (SELECT @amount, @requestID) AS source (amount, request)
ON (target.request = source.request)
WHEN MATCHED THEN
    UPDATE SET amount = source.amount
WHEN NOT MATCHED THEN
    INSERT (request, amount)
    VALUES (source.request, source.amount);
2021-03-23