我想要一个查询将记录从一个表插入到另一个表中的另一个表中,如果目标表已经存在,它应该在表的末尾附加记录.
这个怎么样:
USE TargetDatabase GO INSERT INTO dbo.TargetTable(field1, field2, field3) SELECT field1, field2, field3 FROM SourceDatabase.dbo.SourceTable WHERE (some condition)
如何将表值从一个服务器/数据库插入另一个数据库?
1创建链接服务器{if needs}(SQL server 2008 R2 - 2012) http://technet.microsoft.com/en-us/library/ff772782.aspx#SSMSProcedure
2配置链接服务器以使用凭据a)http://technet.microsoft.com/es-es/library/ms189811(v= sql.105) .aspx
EXEC sp_addlinkedsrvlogin 'NAMEOFLINKEDSERVER', 'false', null, 'REMOTEUSERNAME', 'REMOTEUSERPASSWORD'
- 检查服务器
SELECT * FROM sys.servers
- 测试链接服务器
EXEC sp_testlinkedserver N'NAMEOFLINKEDSERVER'
插入新的本地表
SELECT * INTO NEWTABLE FROM [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE
要么
插入远程表中的新值
INSERT INTO [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE SELECT * FROM localTABLE
插入新的本地表值
INSERT INTO localTABLE SELECT * FROM [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE
这是一个快速简便的方法:
CREATE TABLE database1.employees AS SELECT * FROM database2.employees;
--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. */
你可以试试
Insert into your_table_in_db1 select * from your_table_in_db2@db2SID
db2SID是其他DB的sid.它将出现在tnsnames.ora文件中