Reputation: 19891
What's the right syntax in Sybase SQL to do an update with a self join? E.g. 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!
Upvotes: 2
Views: 14037
Reputation: 5105
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, i.e. 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
Upvotes: 4
Reputation: 52645
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'
Upvotes: 0