patternsqlMinor
Update a column, selected by query
Viewed 0 times
queryupdateselectedcolumn
Problem
Just stumbled upon this stackoverflow question: https://stackoverflow.com/questions/13648898/sql-update-with-row-number. The second answer struck me as odd:
Here, a column
UPDATE x
SET x.CODE_DEST = x.New_CODE_DEST
FROM (
SELECT CODE_DEST, ROW_NUMBER() OVER (ORDER BY [RS_NOM]) AS New_CODE_DEST
FROM DESTINATAIRE_TEMP
) xHere, a column
CODE_DEST is updated with the value of ROW_NUMBER(). However, x.CODE_DEST itself is the result of a select query. So, I'm updating the result of a select query. Is this common practice?Solution
It's not common but it can work. Under certain circumstances (and I'm not sure of the rules) you can update a column from a CTE or subquery. My guess is that it's very similar to being able to update a view and probably has the same rules.
The times I've done it it's quite a bit faster than joining back to the original table and updating it.
The times I've done it it's quite a bit faster than joining back to the original table and updating it.
Context
StackExchange Database Administrators Q#125538, answer score: 4
Revisions (0)
No revisions yet.