简体   繁体   中英

Sybase SQL update with self-join

What's the right syntax in Sybase SQL to do an update with a self join? Eg assuming you have the below table (#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

I want to overwrite the amounts on 2010-12-31 with the amount values from 2010-12-30.

I feel like writing something like this:

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' 

But it doesn't look like Sybase accepts an alias in the 'update <>' clause. What's the proper way of doing this?

Thanks!

This works:

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

If you leave out the alias of the table you are updating, ie set amount = new.amount then Sybase associates the table you are updating with the first matching table in the from clause, so in that case for your update to work you'd need the from to read from #tmptbl new, #tmptbl old .

Output:

 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 

Have you tried

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' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM