Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a row from one SQL Server table to another

Tags:

sql

sql-server

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).

like image 488
rp. Avatar asked Sep 11 '08 17:09

rp.


People also ask

How do I copy a row in SQL Server?

If you right-click the table in SSMS then script the table as INSERT, then do the same again and script the tables as SELECT. Paste this SELECT statement at the end of the INSERT replacing the VALUES clause, then just edit that statement a bit to get the current maximum ID and add a ROW_NUM to it.

How do you copy a table row?

By holding down the Ctrl key, you can copy a Word table's row or column to create a new row or column. Word tables are great tools for listing and comparing values.


2 Answers

As long as there are no identity columns you can just

INSERT INTO TableNew SELECT * FROM TableOld WHERE [Conditions] 
like image 83
Scott Nichols Avatar answered Sep 28 '22 06:09

Scott Nichols


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.

like image 42
Michael Haren Avatar answered Sep 28 '22 05:09

Michael Haren