Search code examples
sqlsql-serversql-updatesubquerysql-delete

How do I add Update statement to selected rows I am about to insert into a table with MS SQL query?


I have been busting my head for some time already and without any result. Honestly I think that I need fresh eyes on this query. I have written a query that deletes data from one table and puts it into another table. What I can't really figure out, is how to update one column for those rows I am moving, within the same query. Here is how the query looks:

INSERT table1_archive
SELECT * FROM (
    DELETE table
       OUTPUT
            DELETED.*
    WHERE <condition1>
) AS RowsToMove;

What I want is to add also

UPDATE table1 SET <my_column> = "" WHERE <condition1>

Since it is the same condition and table for delete and update, I was thinking that it makes no sense to call two different queries to do some actions for exactly the same rows. What I want is to clear data out of the <my_column> either before moving rows to table1_archive, or after doing so.

I guess my question is: How would I apply this update statement to the selected rows I am about to insert into the table1_archive?

ANSWER

This question becomes a little redundant as the UPDATE statement was not necessary to achieve what I wanted. I could just list all my columns in the SELECT statement and replace the <my_column> with NULL, or '''.


Solution

  • You can simply manipulate the column to be updated in the select statement.

     INSERT INTO table1_archive
     SELECT Col1,Col2...,"" AS <my_column> FROM (
     DELETE table
       OUTPUT
            DELETED.*
     WHERE <condition1>
     ) AS RowsToMove;