2011-01-05 25 views
2

Sybase SQL中使用自連接進行更新的正確語法是什麼?例如。假設你有下面的表格(#tmptbl):通過自連接進行的Sybase SQL更新

account | client |amount | date 
------------------------------------- 
ACT1 | CLIENTA | 12 |2010-12-30 
ACT2 | CLIENTB | 5  |2010-12-30 
ACT1 | CLIENTA | 17 |2010-12-31 
ACT2 | CLIENTB | 6  |2010-12-31 

我想覆蓋2010-12-31金額從2010-12-30的金額。

我覺得寫東西是這樣的:

update old 
set old.amount = new.amount 
from #tmptbl old, #tmptbl new 
where 
/*filter old*/ 
old.account = 'ACT1' 
and old.date = '2010-12-30' 
and old.client = 'CLIENTA' 
/* self-join new and old*/ 
and old.account = new.account 
and old.client = new.client 
/* filter new */ 
and new.date = '2010-12-31' 

但它看起來並不像的Sybase接受「更新<>」子句中的別名。這樣做的正確方法是什麼?

謝謝!

回答

4

這工作:

update #tmptbl 
set old.amount = new.amount 
from #tmptbl old, #tmptbl new 
where 
/*filter old*/ 
old.account = 'ACT1' 
and old.date = '2010-12-30' 
and old.client = 'CLIENTA' 
/* self-join new and old*/ 
and old.account = new.account 
and old.client = new.client 
/* filter new */ 
and new.date = '2010-12-31' 
go 

如果你離開了表的別名,你正在更新,即set amount = new.amount那麼的Sybase關聯你與更新表首先在from子句中使用匹配表,所以在這種情況下,爲了使更新工作,您需要從中讀取from #tmptbl new, #tmptbl old

輸出:

account  client  amount  date    
---------- --------- --------- ---------------- 
ACT1  CLIENTA 12   30/12/2010 00:00 
ACT2  CLIENTB 5   30/12/2010 00:00 
ACT2  CLIENTB 6   31/12/2010 00:00 
ACT1  CLIENTA 12   31/12/2010 00:00 
+0

這就是爲什麼當我從「#tmptbl old,#tmptbl new設置new.amount = old.amount」時,我得到了「警告:要更新的模糊表;使用update子句中指定的表。」? – naumcho 2011-01-05 17:03:54

+0

非常有用,謝謝! – 2016-08-25 15:46:52

0

你試過

update #tmptbl 
set amount = new.amount 
from #tmptbl old, #tmptbl new 
where 
/*filter old*/ 
old.account = 'ACT1' 
and old.date = '2010-12-30' 
and old.client = 'CLIENTA' 
/* self-join new and old*/ 
and old.account = new.account 
and old.client = new.client 
/* filter new */ 
and new.date = '2010-12-31' 
+0

是的 - 作品,謝謝。必須接受另一個答案,因爲它更詳細一些。 – naumcho 2011-01-06 19:57:22

+0

@ user779很好。因爲我已經有了一個Sybase數據庫,所以我一直在猜測:) – 2011-01-06 20:01:10