Saturday, 24 August 2013

SQL Server - Uniquely update one table based on category records in another table

SQL Server - Uniquely update one table based on category records in
another table

I have one table that lists customer numbers and promo codes:
CustomerNumber | Promo
12345 | ABCDEF
54321 | BCDEFG
And another table that lists Certificates, Promos, and CustomerNumbers,
but CustomerNumber is initially NULL:
Certificate | Promo | CustomerNumber
1111111111 | ABCDEF | NULL
2222222222 | BCDEFG | NULL
What I need to do is uniquely assign each Certificate in the second table
to a customer in the first table. The promos need to match. Update the
second table with a customer number from the first, only to one record,
with a matching promo.
I've done this in the past with a VB program - loop over records in the
first table, update the first free record for the matching promo in the
second table. But that program takes too long to run (there are usually
around 600,000 records).
Is there any way to do this right in SQL? Accomplish the task with an
awesomely convoluted (or even awesomely simple) SQL query? (Or SQL Server
functionality?)

No comments:

Post a Comment