2010-06-03 76 views
3

我是新來的T-SQL命令MERGE所以我發現我的SQL邏輯的地方,我可以用它,並希望測試,但無法弄清楚我到底如何使用它:如何在這種情況下使用T-SQL MERGE?

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) 

請建議正確的用法。謝謝!

回答

12

你的幫忙看一下?這裏有一個簡單的例子:

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

這是您的簡單示例的簡單演練:) http://stackoverflow.com/a/10219581/261997 – RThomas 2012-04-18 23:31:52

1

我希望它會工作

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) 
+3

的是,插入部分將無法工作,因爲你的源選擇將返回一個空的記錄,它會再嘗試合併 – 2010-06-03 16:41:43

+2

在更新,source.amount從taable commisions_history,但需要來自變量@Amount。 – 2010-06-03 16:44:23

+0

@Tom H,@Shannon Severance: 感謝您的意見。我改變了它。無論如何,湯姆H的更清楚。 – a1ex07 2010-06-03 17:01:41