不使用游标更新删除和插入主表?

时间:2013-09-23 16:54:16

标签: sql sql-server tsql sql-server-2008-r2 insert-update

#TEMP

TomID    Value      Name
634     38.000000   LI
634     38.000000   LI
670     38.000000   LI
722     37.240000   LI
723     37.240000   LI
724     37.240000   LI
634     2.000000    RAN
670     2.000000    RAN
722     1.960000    RAN
723     1.960000    RAN
724     1.960000    RAN
634     20.000000   TAU
670     20.000000   TAU
722     19.600000   TAU
723     19.600000   TAU

MainTable

TomID    Value      Name

166        77         RS
634       38         LI  
723     19.600000   TAU

通过使用Temp表我想将所有行插入主表 条件: 如果TomID和Name是qual,则应在主表中更新该值。 我不想使用游标 你能帮帮我吗

2 个答案:

答案 0 :(得分:1)

您可以使用MERGE语句。 Reference

我认为这会让你得到你想要的东西:

MERGE MainTable AS M
USING (SELECT * FROM #temp) AS T
ON  M.TomID = T.TomID AND M.Name = T.Name
WHEN MATCHED THEN UPDATE 
   SET M.Value = T.Value
WHEN NOT MATCHED THEN 
    INSERT(TomId, Value, Name)
    VALUES(T.TomId, T.Value, T.Name);

答案 1 :(得分:1)

- MERGE声明会有所帮助。

MERGE MainTable AS target
    USING (SELECT TomID, Value,Name from #temp) AS source (TomID, Value, Name)
    ON (target.TomID = source.TomID and target.Name = source.Name)
    WHEN MATCHED THEN 
        UPDATE SET Value = source.Value
    WHEN NOT MATCHED THEN   
        INSERT (TomID, Name,Value)
        VALUES (source.TomID, source.Name,source.Value);

MERGE (Transact-SQL)