Inserting data from a table in database 1 to an identical table in database 2...both databases are on the same server
-
Friday, January 18, 2013 9:51 PM
Hello,
I am probably missing something very easy however, I cannot seem to figure out how to insert data from a table in database 1 to an identical table in database 2. Both databases are on the same server.
Can't I use a simple insert query??
Thanks in advance!
All Replies
-
Friday, January 18, 2013 9:56 PM
You can use:
INSERT INTO NameDatabase1..YourTableOfDB1 SELECT alias.thefieldsOfTableOfDB2 FROM NameDatabase2..YourTableOfDB2 alias
But the user you are using to execute the query needs to have access both databases
please, check this post:
SQL Express Database table data insert into another database
Regards !
Sergio Sánchez Arias
- Edited by SergioSA(chancrovsky)Microsoft Community Contributor Friday, January 18, 2013 9:56 PM
- Edited by SergioSA(chancrovsky)Microsoft Community Contributor Friday, January 18, 2013 10:01 PM
- Proposed As Answer by Naomi NMicrosoft Community Contributor, Moderator Sunday, January 20, 2013 5:34 AM
- Marked As Answer by Iric WenModerator Monday, January 28, 2013 6:00 AM
-
Friday, January 18, 2013 9:59 PM
You can. If you are in database a and need to insert into database b for a table called mytable, you would write something like
INSERT INTO b.dbo.MyTable(col1, col2, col3...) SELECT col1, col2, col3,..... FROM MyTable
Additionally, you may need to handle things like identities. What problems are you facing? Can you please elaborate?
-
Friday, January 18, 2013 10:12 PM
Hi Sergio, thanks for this....I am getting the following error associated with this method.
"An explicit value for the identity column in table 'ambientair..tbl_StationWind' can only be specified when a column list is used and IDENTITY_INSERT is ON."
Any idea why?
Thanks
-
Friday, January 18, 2013 10:18 PM
This error occurs when you're trying to insert data into a table that contains an identity column.
You need to do this:
Before your SQL statement.
--Before your SQL INSERT STATEMENT SET IDENTITY_INSERT <tablename> ON {YOUR SQL INSERT STATEMENT} --After your SQL INSERT STATEMENT: SET IDENTITY_INSERT <tablename> OFFThe tablename is the table are using in your INSERT stament.Sergio Sánchez Arias
- Marked As Answer by Iric WenModerator Monday, January 28, 2013 6:00 AM
-
Friday, January 18, 2013 10:21 PM
try this..
Use DestinationDatabase
GO
set identity_insert dbo.DestinationTable on
INSERT INTO dbo.DestinationTable(col1, col2, col3) SELECT col1, col2, col3 FROM SourceDatabase.schemaName.SourceTable
Hope it Helps!!
-
Friday, January 18, 2013 10:35 PM
Since both table are identical, you might not need to specify the 'Identity' column while you are inserting into the Second table.
INSERT INTO DB2.SchemaName.Table1 (--Col1 (IdentityColumn) ,Col2 ,Col3 ,Col3 ) SELECT --Col1 ,Col2 ,Col3 ,Col3] FROM DB1.SchemaName.Table1
Narsimha

