tags:

views:

9180

answers:

5

I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility).

Thanks rp

+3  A: 
SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >
Jarrett Meyer
+11  A: 

As long as there are no identity columns you can just

INSERT Table2
SELECT * FROM Table1
WHERE [Conditions]
Scott Nichols
Be careful with this syntax as it won't work if Table2 has an identity column and it will break in the future if Table1 ever changes without Table2 changing in sync (burned me before). This solution might be perfect for your case, just be aware of these considerations.
Michael Haren
+10  A: 

Alternative syntax:

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

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

Michael Haren
+3  A: 

"INSERT INTO DestTable SELECT * FROM SourceTable WHERE ..." works in SQL Server.

Kaniu
+6  A: 

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]
ScottStonehouse
@ScottStonehouse: if you collect all the other answers into this answer like you have done but with code (making it comprehensive), you'd definitely become the best answer.
Michael Haren