如何在单个合并语句中执行多次更新

时间:2019-05-30 10:34:14

标签: mysql sql-server oracle

我需要使用两个不同的条件(例如, 1. row_ind = N;更新一些列
2. row_ind = Y;更新一些列

我将如何在sqlserver / oracle中实现这一目标

WHEN MATCHED THEN
UPDATE SET TARGET.NodeId = SOURCE.StartNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind ='Y'

UPDATE SET TARGET.NodeId = SOURCE.EndNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind = 'N';

2 个答案:

答案 0 :(得分:1)

对于tsql,您可以尝试使用AND <clause_search_condition>

MERGE   
    [ TOP ( expression ) [ PERCENT ] ]   
    [ INTO ] <target_table> [ WITH ( <merge_hint> ) ] [ [ AS ] table_alias ]  
    USING <table_source>   
    ON <merge_search_condition>  
    [ WHEN MATCHED [ AND <clause_search_condition> ]     <==
        THEN <merge_matched> ] [ ...n ]  
<merge_matched>::=  
     { UPDATE SET <set_clause> | DELETE } 

由于AND之后您可以具有多个WHEN MATCHED,且条件不同,因此您可以使用单个merge语句创建多个更新。

WHEN MATCHED AND row_ind ='Y' THEN
UPDATE SET TARGET.NodeId = SOURCE.StartNodeId,
           TARGET.LinkId = SOURCE.Id 
WHEN MATCHED AND row_ind ='N' THEN
UPDATE SET TARGET.NodeId = SOURCE.EndNodeId,
           TARGET.LinkId = SOURCE.Id ;

oracle中,您不能执行此操作,因为只允许一个merge_update_clause

MySQL不支持MERGE

答案 1 :(得分:1)

您可以使用“ CASE..WHEN”在Oracle中实现以下目的:

WHEN MATCHED THEN UPDATE SET TARGET.NODEID = CASE ROW_IND
    WHEN 'Y'   THEN SOURCE.STARTNODEID
    WHEN 'N'   THEN SOURCE.ENDNODEID
END,
TARGET.LINKID = SOURCE.ID;

谢谢