USING Common Table Expression and perform multiple update commands
A SQL Server UPDATE
only allows you to update a single table. As buried in the documentation:
The following example updates rows in a table by specifying a view as the target object. The view definition references multiple tables, however, the
UPDATE
statement succeeds because it references columns from only one of the underlying tables. TheUPDATE
statement would fail if columns from both tables were specified.
Although views and CTEs are not exactly the same thing, they often follow similar rules. So, this is also explained in the section on updatable views:
Any modifications, including
UPDATE
,INSERT
, andDELETE
statements, must reference columns from only one base table.
You can effectively do what you want by issuing two updates and wrapping them in a single transaction.
You can insert your CTE
result to a @Table
variable and use this Table wherever required in the code block. (You can join
this Table with actual table to perform the UPDATE/INSERT/DELETE
etc). You can't use the same CTE in multiple statement, because CTE is part of the subsequent statement only.