Question

I misremembered what the key was for this Templates table and therefore I added the wrong field as a foreign key. Now I need to add the foreign key and I want to populate its values based on this other field that is already populated. I started trying to do this with an update statement, but I'm not sure how to do it.

Part of my schema:

Products Table:

ProductName (key)
TemplateName
TemplateID
...

I've added TemplateID, but it has no data in it yet and is nullable.

Templates Table:

TemplateID (key)
TemplateName
...

I want to use the Templates table to find the matching TemplateID for each TemplateName in the Products table and fill that in the foreign key reference in the Products table.

Can I do this with a subquery in Update, or do I need to write some kind of Stored Proc? I'm using Sql Server 2008

Was it helpful?

Solution

You can do it with a simple UPDATE query

UPDATE Products
SET Products.TemplateID = Templates.TemplateID
FROM Templates
WHERE Templates.TemplateName = Products.TemplateName

You do not need to specify the Products table in the FROM clause, nor a JOIN clause. Just specify the Templates table in the FROM clause. You can use the tablename you use in the UPDATE clause in the WHERE clause, to correlate recordds from both tables.

OTHER TIPS

Here's a join solution. It's significant in that only the matched rows will be updated.

Update p
Set p.TemplateId = t.TemplateId
From Products p
  join Templates t
  On p.TemplateName = t.TemplateName

Here's the subquery solution. Every row of Products will be updated, even when there is no match.

Update p
Set p.TemplateId =
(
  Select t.TemplateId
  From Templates t
  Where p.TemplateName = t.TemplateName
)
From Products p
update Templates
set TemplateId=Products.TemplateId
from Templates
inner join Products
   on Templates.TemplateName=Products.TemplateName
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top