07-08-2008

SQL Copy query

This query duplicates the rows inside a table:

INSERT INTO tablename2 (fieldname1, fieldname2, fieldname3, fieldname4) 
	SELECT fieldname1, fieldname2, fieldname3,fieldname4 FROM tablename1
 
-- Or if the tables are identical:
 
INSERT INTO tablename1 SELECT * FROM tablename2

Specify another table name to duplicate rows inside one table to another table

INSERT INTO tablename2 (fieldname1, fieldname2, fieldname3, fieldname4) 
	SELECT fieldname1, fieldname2, fieldname3,fieldname4 FROM tablename1

You can of course specify values to change certain values whilst copying:

INSERT INTO tablename2 (fieldname1, fieldname2, fieldname3, fieldname4) 
	SELECT value1, fieldname2, value3, fieldname4 FROM tablename1

And to Copy accross to another sql server on the network (MS SQL Server):

sp_addlinkedserver SERVERNAME
 
INSERT INTO SERVERNAME.DBname.dbo.tablename1 (fieldname2,fieldname1) SELECT fieldname2,fieldname1 FROM tablename2

If there is a identity column defined:

SET IDENTITY_INSERT tablename ON 
 

To only copy only the values from table column from on to a corresponding database column on another table:

update table1
set fieldname = x.fieldname
from tablename i
inner join tablename2 x
on i.id=x.id

Comments:

Your comment:

»

 

[x]