HOWTO: Update Records in a Database Table With Data From Another Table (MS SQL Server)
SQL's UPDATE statement makes it easy to update one or more records in a database table. The most common UPDATE statement pattern assigns static or parameterized values to one or more columns:
UPDATE MyTable SET
Column1 = Value1,
Column2 = Value2,
...
WHERE PrimaryKeyColumn = SomeValue
But what if you need to update values in one database table from values in another database table? There are a couple ways this can be done. One way is to use a subquery:
UPDATE MyTable SET
Column1 = (SELECT SomeColumn FROM SomeOtherTable WHERE SuchAndSuch = ThisAndThat),
Column2 = (SELECT SomeOtherColumn FROM SomeOtherTable WHERE SuchAndSuch = ThisAndThat),
...
WHERE PrimaryKeyColumn = SomeValue
Alternatively, you can use a JOIN statement in your UPDATE clause. The precise syntax seems to vary a bit based on the database system. For Microsoft SQL Server, use the following syntax:
UPDATE MyTable SET
Column1 = SomeOtherTable.SomeColumn,
Column2 = SomeOtherTable.SomeOtherColumn,
...
FROM MyTable
INNER JOIN SomeOtherTable ON
MyTable.SuchAndSuch = SomeOtherTable.ThisAndThat
WHERE PrimaryKeyColumn = SomeValue
Bear in mind that updating data in one table with data from another table may be a sign of bad database design. I've seen developers use these approaches to duplicate data across multiple tables so that it's "easier" or "quicker" to write a query to read the data, but such actions are (usually) folly. Data duplication may make your SELECT queries easier to write, but you can very easily end up with data integrity issues.
So when might you need to copy data from one table to another? Consider a help desk application that allows support staff to create support tickets, where each ticket in the system exists as a record in the Tickets table. A ticket may have dozens of data points. To ease data entry, let's say that administrative users can create "ticket templates," which pre-define the values for a number of ticket data points that are stored in a table named TicketTemplates. Applying a template to an existing ticket would require that the existing record in the Tickets table have its non-set data points assigned to the corresponding default values of the selected template. Presume that the Tickets table has a TicketTemplateId field that indicates what template is to be applied to the ticket. Once this value has been assigned, the following UPDATE statement could be executed to copy the template's pre-defined values to the non-assigned data points in the Tickets table:
UPDATE Tickets SET
PriorityId = ISNULL(Tickets.PriorityId, TicketTemplates.PriorityId),
CategoryId = ISNULL(Tickets.CategoryId, TicketTemplates.CategoryId),
IsPublic = ISNULL(Tickets.IsPublic, TicketTemplates.IsPublic),
...
FROM Tickets
INNER JOIN TicketTemplates ON
Tickets.TicketTemplateId = TicketTemplates.TicketTemplateId
WHERE Tickets.TicketId = @TicketId
Happy Programming!