Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 UPDATE / SubQuery / Correlated?

Author  Topic 

JarWithLid
Starting Member

10 Posts

Posted - 2009-06-23 : 13:29:33
Greetings,

I have two tables:

[customer_serialnumbers] - contains customers serial numbers
(has PK serialnumber, ordernum (original order for license))

[subscriptions] - contains customers support subscriptions
(has column ordernum (original order for license))

subscriptions now has a new column, snum, that is a FK to customer_serialnumbers.serialnumber. I need to update subscriptions.sum to point at the serial number (customer_serialnumbers.serialnumber) the subscription refers to. Only one subscription can point at one serial number.

Most of the legwork can be done by looking for serial numbers and subscriptions that were on the same order. So, in psuedocode, I need to do this:


foreach (subscription) :
update snum column to customer_serialnumbers.serialnumber where:
- the customer_serialnumbers.ordernum = subscription.ordernum
- customer_serialnumbers.serialnumber is not yet consumed by another row in subscriptions
endforeach;


I was hoping the innermost subquery would take care of the bold condition above. It doesn't seem to be as I'm getting duplicates. Little help?


update subscriptions
set snum = ( -- get a serialnumber from the customerserialnumber list
select top 1 serialnumber
from customer_serialnumbers cs
where cs.ordernum = subscriptions.ordernum -- snum order same as subs order
-- don't join to a revoked snum
and cs.active = 1
-- snum not already used
and serialnumber not in (
select distinct(snum)
from subscriptions
where snum is not null
)
)
where subscriptions.snum is null -- don't set something we've already set



THANKS!
Adam

p.s. an order can have multiple serial numbers and subscriptions on it, that's matching via ordernum isn't a 1-1 relationship.
   

- Advertisement -