USE TargetDatabase
GO
INSERT INTO dbo.TargetTable(field1, field2, field3)
SELECT field1, field2, field3
FROM SourceDatabase.dbo.SourceTable
WHERE (some condition)
--Code for same server
USE [mydb1]
GO
INSERT INTO dbo.mytable1 (
column1
,column2
,column3
,column4
)
SELECT column1
,column2
,column3
,column4
FROM [mydb2].dbo.mytable2 --WHERE any condition
/*
steps-
1- [mydb1] means our opend connection database
2- mytable1 the table in mydb1 database where we want insert record
3- mydb2 another database.
4- mytable2 is database table where u fetch record from it.
*/
--Code for different server
USE [mydb1]
SELECT *
INTO mytable1
FROM OPENDATASOURCE (
'SQLNCLI'
,'Data Source=XXX.XX.XX.XXX;Initial Catalog=mydb2;User ID=XXX;Password=XXXX'
).[mydb2].dbo.mytable2
/* steps -
1- [mydb1] means our opend connection database
2- mytable1 means create copy table in mydb1 database where we want
insert record
3- XXX.XX.XX.XXX - another server name.
4- mydb2 another server database.
5- write User id and Password of another server credential
6- mytable2 is another server table where u fetch record from it. */
If both the tables have the same schema then use this query:
insert into database_name.table_name select * from new_database_name.new_table_name where='condition'
Replace database_name with the name of your 1st database and table_name with the name of table you want to copy from
also replace new_database_name with the name of your other database where you wanna copy and new_table_name is the name of the table.