sql跨库查询

方式一:

使用连接服务器

sp_addlinkedserver 'mylink','','SQLOLEDB','(local)'
sp_addlinkedsrvlogin 'mylink','false',null,'sa','sa'
select * from [mylink].test.dbo.Student

或者在 对象资源管理器-服务器对象-连接服务器 里添加

 

方式二:

相同实例的情况下

直接select * from [AAA]..Table1 a inner join [BBB]..Table2 b on a.id1 = b.id2

在数据库名和表名之间放两个点或者[AAA].dbo.Table1

 

方式三:

使用 OPENROWSET/OPENDATASOURCE,据说不是很稳定

OPENDATASOURCE速度较慢

--启用OPENROWSET/OPENDATASOURCE支持

exec sp_configure 'show advanced options',1
reconfigure
exec sp_configure 'Ad Hoc Distributed Queries',1
reconfigure
go
Select a.* FROM OPENROWSET('SQLOLEDB','(local)';'sa';'sa','Select * FROM [test].dbo.Student') AS a
Select a.* FROM OPENROWSET('MSDASQL','DRIVER={SQL Server};SERVER=(local);UID=sa;PWD=sa',test.dbo.Student) AS a
select    * From  OPENDATASOURCE('SQLOLEDB','Data Source=(local);User ID=sa;Password=richen').test.dbo.Student
go

--安全起见,关闭OPENROWSET/OPENDATASOURCE支持
exec sp_configure 'Ad Hoc Distributed Queries',0
reconfigure
exec sp_configure 'show advanced options',0
reconfigure
go

posted @ 2010-10-08 10:38  sweetjian  阅读(223)  评论(0编辑  收藏  举报