如何使用Oracle中多列的内部联接进行更新

时间:2016-11-17 09:59:23

标签: sql oracle

获取错误00933. 00000 - "SQL command not properly ended"

UPDATE users SET                  
          username     = a.username,                  
          groupcode    = a.groupcode,             
          adauth       = a.adauth,               
          userlevel    = a.userlevel,                
          locationcd   = a.locationcd,            
          panno        = a.panno,                
          authrej      = a.authrej,                  
          multilogin   = a.multilogin,                 
          loginstatus  = a.loginstatus,                
          userstatus   = a.userstatus,                
          lupdnuser    = a.lupdnuser,                
          lupdndt      = a.lupdndt,                 
          createdby    = p_cUserId  ,                  
          createddt    = SYSTIMESTAMP,                
          closedby     = a.closedby ,                 
          closeddt     = a.closeddt ,                 
          emailid      = a.emailid  ,      
          passwordattempt =  CASE  cast ( a.userstatus as varchar)  WHEN '01' THEN  0  ELSE a.passwordattempt END                    
          FROM   userstrans a                      
          INNER  JOIN users b ON                    
          a.userid    = b.userid         
          AND a.sysuserno   =  b.sysuserno                         
          WHERE  a.systrnno     = p_nSysTrnNo                 
          AND   a.trnmode      = 'EDIT'                  
         AND   a.trnid        = 'N';   

1 个答案:

答案 0 :(得分:0)

进行此类更新的最佳方式是使用MERGE语句,正如Aleksej在评论中所建议的那样。 MERGE非常容易学习和使用(特别是如果你已经熟悉UPDATE,INSERT和DELETE),它非常灵活,有时比UPDATE更有效(执行中)。

或者,您可以使用JOIN重写UPDATE以遵守正确的Oracle语法。 MERGE和UPDATE / JOIN都假定连接条件(MERGE的匹配条件)在源表中为目标表中的每一行标识唯一行;这不是一个限制(正如一些人可能认为的那样),而是首先要使更新有意义的逻辑要求。

使用JOIN的UPDATE应如下所示:

update 
  ( select b.username  as b_username , a.username  as a_username ,
           b.groupcode as b_groupcode, a.groupcode as a_groupcode,
           ETC.
    from   users b inner join userstrans a on b.userid    = a.userid 
                                          and b.sysuserno = a.sysuserno )
set b_username = a_username,   ETC.
where   <WHERE conditions here>
;

将MERGE解决方案与此UPDATE与JOIN解决方案进行比较 - 您将会欣赏MERGE的清晰程度!