日期:2014-05-17  浏览次数:20352 次

不同服务器数据库关联查询的问题。
SQL code

--192.168.1.1服务器数据库
create database db1
GO
use db1

GO
create table table1(
tid int,
tname varchar(50))

GO
insert table1(tid,tname)
select 1,'子敬' union
select 2,'文远' union
select 3,'文长' 




--192.168.1.2服务器数据库
create database db2
GO
use db2

GO
create table table2(
tid int,
tname varchar(50))

GO
insert table2(tid,tname)
select 2,'文远' union
select 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'         --删除连接