SQL Server将所有行从一个表复制到另一个表,即复制表

时间:2010-04-22 13:59:56

标签: sql sql-server-2008 ssms

我想将一张表作为历史记录,并将其替换为空表。如何通过Management Studio完成此操作?

6 个答案:

答案 0 :(得分:30)

将您的表复制到要存档的表中:

SELECT * INTO ArchiveTable FROM MyTable

删除表格中的所有条目:

DELETE * FROM MyTable

答案 1 :(得分:21)

select * into x_history from your_table_here;
truncate table your_table_here;

答案 2 :(得分:17)

没有sql server可以测试,但我认为它只是:

insert into newtable select * from oldtable;

答案 3 :(得分:8)

您可以使用RAW SQL:

INSERT INTO DEST_TABLE (Field1, Field2) 
SELECT Source_Field1, Source_Field2 
FROM SOURCE_TABLE

或使用向导:

  1. 右键单击数据库 - >任务 - >导出数据
  2. 选择源/目标数据库
  3. 选择源/目标表和 字段
  4. 复制数据
  5. 然后执行:

    TRUNCATE TABLE SOURCE_TABLE
    

答案 4 :(得分:2)

尝试使用单个命令来删除和插入数据

DELETE MyTable
    OUTPUT DELETED.Col1, DELETED.COl2,...
        INTO MyBackupTable

工作样本:

--set up the tables
DECLARE @MyTable table (col1 int, col2 varchar(5))
DECLARE @MyBackupTable table (col1 int, col2 varchar(5))
INSERT INTO @MyTable VALUES (1,'A')
INSERT INTO @MyTable VALUES (2,'B')
INSERT INTO @MyTable VALUES (3,'C')
INSERT INTO @MyTable VALUES (4,'D')

--single command that does the delete and inserts
DELETE @MyTable
    OUTPUT DELETED.Col1, DELETED.COl2
        INTO @MyBackupTable

--show both tables final values
select * from @MyTable
select * from @MyBackupTable

输出:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(4 row(s) affected)
col1        col2
----------- -----

(0 row(s) affected)

col1        col2
----------- -----
1           A
2           B
3           C
4           D

(4 row(s) affected)

答案 5 :(得分:-2)

这将有效:

select * into DestinationDatabase.dbo.[TableName1] from (
Select * from sourceDatabase.dbo.[TableName1])Temp