如何将行从一个 SQLServer 表复制到另一个表

我有两个相同的表,需要将行从一个表复制到另一个表。最好的方法是什么?(我只需要通过编程方式复制几行,不需要使用批量复制实用程序)。

264628 次浏览
SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >

As long as there are no identity columns you can just

INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]

Alternative syntax:

INSERT tbl (Col1, Col2, ..., ColN)
SELECT Col1, Col2, ..., ColN
FROM Tbl2
WHERE ...

The select query can (of course) include expressions, case statements, constants/literals, etc.

INSERT INTO DestTable
SELECT * FROM SourceTable
WHERE ...

works in SQL Server

Jarrett's answer creates a new table.

Scott's answer inserts into an existing table with the same structure.

You can also insert into a table with different structure:

INSERT Table2
(columnX, columnY)
SELECT column1, column2 FROM Table1
WHERE [Conditions]

To select only few rows..This will work like charm..

SELECT TOP 10 *
INTO db2.dbo.new_table
FROM db1.dbo.old_table;

Note : Just create a new table in the required db..We need not define its structure.