2016-02-09 100 views
0

讓我們假設table1爲a,table2爲b,它們都是不同的結構,但是有相同的字段叫branch,我想插入table2.branchtable1.branchSQL更新,如何向table1插入table2的值

我已經嘗試過這樣的:

update a         
set a.branch = b.branch     
from table1 a        
inner join table2 b       
on a.table1id = b.table2id      
where (b.asd = '1' or b.asd = '3') 
and b.branch <> a.branch 

錯誤消息 「列資格賽或表B中未定義」。

update table1 a join table2 b on a.id=b.id 
set a.branch = b.branch 
where a.something <> b.something 

它彈出column b not specified

我曾經嘗試都,但沒有人能夠做到。有沒有人有建議如何更新這個SQL?

+0

能否請你澄清你的意思是:'這是彈出「B列未指定」' – PKirby

+0

消息錯誤是 – ray

+0

你試過我下面提供的腳本? – PKirby

回答

0

請嘗試以下方法:

UPDATE table1 
SET a.branch = b.branch 
FROM table1 a 
INNER JOIN table2 b 
    ON a.id = b.id 
WHERE a.something <> b.something 

希望這有助於。

0

嘗試

update table1 set branch = b.branch     
from table1 a        
inner join table2 b       
on a.table1id = b.table2id      
where (b.asd = '1' or b.asd = '3') 
and b.branch <> a.branch 

需要的表對象要更新不應使用別名

+0

也不行,還是列B未定義 – ray

0

你可以使用一個觸發器,所以當table2.branch插入它就會自動添加到table1.branch

希望這有助於

1

DB2 for i遵循SQL標準,不允許加入更新。看看在reference manualUPDATE

這將在大多數版本的DB2的工作支持的語法我

update table1 a         
set a.branch = (select b.branch 
       from table2 b 
       where a.table1id = b.table2id 
        and b.asd = '1' or b.asd = '3'     
       ) 

然而,上面會更新表1中的每一行從表2的相應值。如果table2中不存在一行,它將嘗試用NULL更新a.branch。如果a.branch不可用,你會得到一個錯誤。有兩種方法。

與它更新表1的當前值

update table1 a         
set a.branch = coalesce((select b.branch 
       from table2 b 
       where a.table1id = b.table2id 
        and b.asd = '1' or b.asd = '3'     
       ), a.branch) 

或者只更新table1中有表2中匹配的行

update table1 a         
set a.branch = (select b.branch 
       from table2 b 
       where a.table1id = b.table2id 
        and b.asd = '1' or b.asd = '3'     
       ) 
where exists (select * 
       from table2 b 
       where a.table1id = b.table2id 
       and b.asd = '1' or b.asd = '3'     
      ) 

如果你在DB2對我支持的版本,你可以使用新的MERGE語句。

merge into table1 t 
using (select a.table1id, b.branch 
     from table1 a        
      inner join table2 b       
      on a.table1id = b.table2id      
     where (b.asd = '1' or b.asd = '3') 
      and b.branch <> a.branch 
     ) as M 
on t.table1id = m.table1id 
when matched 
    then update set t.branch = m.branch 
相關問題