SQL中的用例用于插入或更新

时间:2015-11-11 18:48:18

标签: sql-server

我有包含多行的临时表和具有以下结构的原始表:

temp:desc,id

原文:姓名,身份证,费率

我必须检查一行的id是否与原始的匹配然后我必须更新原始的速率否则我必须在原始中插入行,这一切都应该在循环中发生,因为我们在临时表中有多个记录。 我在SQL SERVER 2008中工作

2 个答案:

答案 0 :(得分:2)

你不需要循环;你可以通过更新然后插入来执行此操作:

UPDATE Original
SET rate = /* whatever the new rate is */
FROM Original
INNER JOIN temp on Original.id = temp.id

INSERT INTO Original (name, id, rate)
SELECT desc, id, /* whatever the rate is */ FROM temp
WHERE id NOT IN (SELECT id FROM Original)

答案 1 :(得分:0)

看起来MERGE可能是一个不错的选择:

-- MERGE statement with the join conditions specified correctly.
USE tempdb;
GO
BEGIN TRAN;
MERGE Target AS T
USING Source AS S
ON (T.EmployeeID = S.EmployeeID) 
WHEN NOT MATCHED BY TARGET AND S.EmployeeName LIKE 'S%' 
    THEN INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName)
WHEN MATCHED 
    THEN UPDATE SET T.EmployeeName = S.EmployeeName
WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'
    THEN DELETE 
OUTPUT $action, inserted.*, deleted.*;
ROLLBACK TRAN;
GO 

从下方直接选择

https://technet.microsoft.com/en-us/library/bb522522(v=sql.105).aspx