- SQL code
--192.168.1.1服务器数据库create database db1GOuse db1GOcreate table table1(tid int,tname varchar(50))GOinsert table1(tid,tname)select 1,'子敬' unionselect 2,'文远' unionselect 3,'文长' --192.168.1.2服务器数据库create database db2GOuse db2GOcreate table table2(tid int,tname varchar(50))GOinsert table2(tid,tname)select 2,'文远' unionselect 3,'文长'
代码如上,db1和db2分别在两台服务器的数据库上。我现在想查询服务器192.168.1.1上的db1表table1的数据,条件是,这些数据的ID必须与192.168.1.2服务器数据库对应。
结果如下:
table1
tid tanme
2 文远
3 文长
------解决方案--------------------------------------------------------
在192.168.1.1的db1上执行
- SQL code
exec sp_addlinkedserver 'srv_lnk','','SQLOLEDB','192.168.1.2' exec sp_addlinkedsrvlogin 'srv_lnk','false',null,'sa','123456'select * from table1 left join srv_lnk.db2.dbo.table2 tb2 on table1.tid=tb2.tid exec sp_dropserver 'srv_lnk','droplogins' --删除连接