2

Sybase SQL 中使用自联接进行更新的正确语法是什么?例如,假设您有下表 (#tmptbl):

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-30 的金额值覆盖 2010-12-31 的金额。

我想写这样的东西:

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 在“update <>”子句中接受别名。这样做的正确方法是什么?

谢谢!

4

2 回答 2

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.amountSybase 将您要更新的表与 from 子句中的第一个匹配表相关联,因此在这种情况下,要使您的更新工作,您需要 from to read 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 
于 2011-01-05T16:14:17.660 回答
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' 
于 2011-01-05T16:12:43.180 回答