How to use T-SQL MERGE in this case?

2019-04-11 16:41发布

问题:

I'm new to T-SQL command MERGE so I found a place in my SQL logic where I can use it and want to test it but can't figure out how exactly should I use it:

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)

Please suggest the proper usage. Thanks!

回答1:

Did you look in the help? Here's a simple example:

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);


回答2:

I hope it will work

MERGE commissions_history AS target
USING (SELECT request FROM  commissions_history WHERE request = @requestID) AS source (request)
ON (target.request = source.request)
WHEN MATCHED THEN 
    UPDATE SET amount = @amount
WHEN NOT MATCHED BY SOURCE    
    INSERT (request, amount)
    VALUES (@requestID,  @amount)