[英]Sybase SQL update with self-join
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 <>'子句中似乎不接受别名。 这样做的正确方法是什么?
谢谢!
这有效:
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子句中的第一个匹配表相关联,因此在这种情况下, set amount = new.amount
更新set amount = new.amount
需要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
你有没有尝试过
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.