【问题标题】:How to do - SQL Update scenario using Join condition on multiple columns and exclude column in join condition if null怎么办 - SQL 更新方案在多列上使用联接条件,如果为空,则在联接条件中排除列
【发布时间】:2020-05-13 01:21:36
【问题描述】:

我有 2 个表 A 和 B,需要使用 c1、c2、c3、c4 作为连接条件,将表 A 的 UCode 更新为表 B 的 UCode。棘手的部分是我应该在连接条件上忽略表 b 中的非空列 例如如下所示,表 B 连接条件应考虑第一行 4 列,第二行仅 3 列,第三行仅 2 列,依此类推

表 A

 ID   UCode    c1    c2    c3   c4
 100           abc   xy    pq   rs
 200           ab    bc    cd   ef
 300           aa    bb    cc   
 400           uu    pp    kk   mn 

表 B

 c1    c2    c3  c4    UCode
 abc   xy    pq   rs   UC11    
 ab    bc    cd        UC22    --Ignore c4 on join condition
 aa    bb              UC44    --Ignore c3,c4 on join condition
 uu                    UC55    --Ignore c2, c3, c4 on join condition

感谢任何帮助。

【问题讨论】:

    标签: sql-server-2008 sql-update


    【解决方案1】:

    不确定我是否理解您想要的结果,但我认为您可以在连接条件中对表 B 列进行一些检查:

    declare @tableA table (ID int,  UCode varchar(10), c1 varchar(10), c2 varchar(10),c3 varchar(10),c4 varchar(10))
    declare @tableB table (c1 varchar(10), c2 varchar(10), c3 varchar(10),c4 varchar(10), UCode varchar(10))
    
    insert into @tableA
    values
      (100, null, 'abc', 'xy','pq',   'rs' )
     ,(200, null, 'ab' , 'bc','cd',   'ef' )
     ,(300, null, 'aa' , 'bb','cc',   null )
     ,(400, null, 'uu' , 'pp','kk',   'mn' )
    
    
     insert into @tableB
    values
     ('abc',   'xy',     'pq'   ,'rs' ,'UC11')    
    ,('ab' ,   'bc',     'cd'   ,null ,'UC22')  
    ,('aa' ,   'bb',     null   ,null ,'UC44')    
    ,('uu' ,   null,     null   ,null ,'UC55')    
    
    update
        @tableA
    set UCode= b.UCode
    from 
        @tableA as a
            inner join 
        @tableB as b 
            on 
            a.c1=b.c1 
        and (b.c2 is null or a.c2=b.c2) 
        and (b.c2 is null or a.c2=b.c2) 
        and (b.c3 is null or a.c3=b.c3) 
        and (b.c4 is null or a.c4=b.c4) 
    

    更新语句后表A如下所示:

    【讨论】:

    • 谢谢安德里亚,会试试这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2019-05-31
    • 2019-08-10
    • 2022-09-23
    • 1970-01-01
    • 2019-08-16
    • 2021-12-17
    相关资源
    最近更新 更多