jueves, 3 de febrero de 2011

SQL Server: Update a table based on another table

When I worked in a small software factory many years ago (it was my first IT job) I always wanted to know how to do this, and couldn't find satisfactory solutions in the web. Now that I'm back to SQL Server programming, it was time to unveil this mistery. Here it goes!


UPDATE TargetTable SET
Field1 = t1.Value1,
Field2 = t2.Value2
FROM OtherTable T1
LEFT JOIN YetAnotherTable T2 ON T1.SomeID = T2.ID
WHERE T1.ID = 1


So there you have it. It is very simple and it can be very handy, specially in stored procedures where sometimes you want to make the less Select instructions possible.


You can also do the same using INSERT SELECT FROM, but that's very easy to find on the web.


Have fun refactoring!

No hay comentarios:

Publicar un comentario