Move SQL data from one table to another

后端 未结 13 2853
梦如初夏
梦如初夏 2020-11-29 20:34

I was wondering if it is possible to move all rows of data from one table to another, that match a certain query?

For example, I need to move all table rows from Tab

相关标签:
13条回答
  • 2020-11-29 21:15

    Yes it is. First INSERT + SELECT and then DELETE orginals.

    INSERT INTO Table2 (UserName,Password)
    SELECT UserName,Password FROM Table1 WHERE UserName='X' AND Password='X'
    

    then delete orginals

    DELETE FROM Table1 WHERE UserName='X' AND Password='X'
    

    you may want to preserve UserID or someother primary key, then you can use IDENTITY INSERT to preserve the key.

    see more on SET IDENTITY_INSERT on MSDN

    0 讨论(0)
  • 2020-11-29 21:17

    Should be possible using two statements within one transaction, an insert and a delete:

    BEGIN TRANSACTION;
    INSERT INTO Table2 (<columns>)
    SELECT <columns>
    FROM Table1
    WHERE <condition>;
    
    DELETE FROM Table1
    WHERE <condition>;
    
    COMMIT;
    

    This is the simplest form. If you have to worry about new matching records being inserted into table1 between the two statements, you can add an and exists <in table2>.

    0 讨论(0)
  • 2020-11-29 21:17

    If the two tables use the same ID or have a common UNIQUE key:

    1) Insert the selected record in table 2

    INSERT INTO table2 SELECT * FROM table1 WHERE (conditions)
    

    2) delete the selected record from table1 if presents in table2

    DELETE FROM table1 as A, table2 as B WHERE (A.conditions) AND  (A.ID = B.ID)
    
    0 讨论(0)
  • 2020-11-29 21:20

    This is an ancient post, sorry, but I only came across it now and I wanted to give my solution to whoever might stumble upon this one day.

    As some have mentioned, performing an INSERT and then a DELETE might lead to integrity issues, so perhaps a way to get around it, and to perform everything neatly in a single statement, is to take advantage of the [deleted] temporary table.

    DELETE FROM [source]
    OUTPUT [deleted].<column_list>
    INTO [destination] (<column_list>)
    
    0 讨论(0)
  • 2020-11-29 21:21

    You should be able to with a subquery in the INSERT statement.

    INSERT INTO table1(column1, column2) SELECT column1, column2 FROM table2 WHERE ...;
    

    followed by deleting from table1.

    Remember to run it as a single transaction so that if anything goes wrong you can roll the entire operation back.

    0 讨论(0)
  • 2020-11-29 21:21

    You could try this:

    SELECT * INTO tbl_NewTableName 
    FROM tbl_OldTableName
    WHERE Condition1=@Condition1Value
    

    Then run a simple delete:

    DELETE FROM tbl_OldTableName
    WHERE Condition1=@Condition1Value
    
    0 讨论(0)
提交回复
热议问题