Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 How to copy a table to other table?

Author  Topic 

allan8964
Posting Yak Master

249 Posts

Posted - 2012-01-01 : 14:00:11
Happy New Year to everyone!

I have a table1 and table2 which have same structure but different data. How can I copy all (or part of) the data from table2 into table1? Thanks in advance.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-01-01 : 15:04:04
[code]INSERT INTO TABLE1
(col1, col2, col3)
SELECT
col1,
col2,
col3
FROM
TABLE2[/code]Also look at this page: http://msdn.microsoft.com/en-us/library/h54fa37c(v=VS.80) I think example 3 on that page may be incorrect. It seems to have two extra semi-colons that may cause the parser to complain.

If you have identity columns in TABLE2, there are some caveats, but otherwise, this should work.
Go to Top of Page

allan8964
Posting Yak Master

249 Posts

Posted - 2012-01-01 : 16:34:24
thanks. but if the tables have many cols (20 cols for example) is there any easier way, I mean not write all the cols if it copy to all cols?
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2012-01-01 : 16:36:16
Depends if you have an identity column in there. If you don't, then you can use * in the select and exclude the column list in the insert. If you do have an identity column, then you'll need to include the column names. SSMS can easily script this out for you. I never type that out.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

Muzaffar557
Starting Member

11 Posts

Posted - 2012-01-02 : 03:40:29
SELECT * INTO #temp FROM <YourTable>

-----------------
The new #temp table is created with exact same copy
even you can use dbo.<tableName>
But its better to have temp table so that you can update or check the data .
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2012-01-03 : 05:59:24
quote:
Originally posted by Muzaffar557

SELECT * INTO #temp FROM <YourTable>

-----------------
The new #temp table is created with exact same copy
even you can use dbo.<tableName>
But its better to have temp table so that you can update or check the data .


This is not required in this case. Also the target table will not have any indices that shource table has.

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -