Move SQL data from one table to another

后端 未结 13 2870
梦如初夏
梦如初夏 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:34

    You may use "Logical Partitioning" to switch data between tables:

    By updating the Partition Column, data will be automatically moved to the other table:

    here is the sample:

    CREATE TABLE TBL_Part1
    (id  INT NOT NULL,
     val VARCHAR(10) NULL,
     PartitionColumn  VARCHAR(10) CONSTRAINT CK_Part1 CHECK(PartitionColumn = 'TBL_Part1'),
     CONSTRAINT TBL_Part1_PK PRIMARY KEY(PartitionColumn, id)
    );
    
    CREATE TABLE TBL_Part2
    (id  INT NOT NULL,
     val VARCHAR(10) NULL,
     PartitionColumn  VARCHAR(10) CONSTRAINT CK_Part2 CHECK(PartitionColumn = 'TBL_Part2'),
     CONSTRAINT TBL_Part2_PK  PRIMARY KEY(PartitionColumn, id)
    );
    
    GO
    
    CREATE VIEW TBL(id, val, PartitionColumn)
    WITH SCHEMABINDING
    AS
         SELECT id, val, PartitionColumn FROM dbo.TBL_Part1
         UNION ALL  
         SELECT id, val, PartitionColumn FROM dbo.TBL_Part2;
    
    GO
    
    --Insert sample to TBL ( will be inserted to Part1 )
    INSERT INTO TBL
    VALUES(1, 'rec1', 'TBL_Part1');
    
    INSERT INTO TBL
    VALUES(2, 'rec2', 'TBL_Part1');
    
    GO
    
    --Query sub table to verify
    SELECT * FROM TBL_Part1
    
    GO
    --move the data to table TBL_Part2 by Logical Partition switching technique
    UPDATE TBL
      SET
          PartitionColumn = 'TBL_Part2';
    
    GO
    
    --Query sub table to verify
    SELECT * FROM TBL_Part2
    

提交回复
热议问题