sqlserver跨数据库操作

来源:互联网 发布:linux使用中文输入法 编辑:程序博客网 时间:2024/05/22 03:14

 

1、方法一:创建链接服务器

--创建链接服务器  
exec   sp_addlinkedserver     'srv_lnk','','SQLOLEDB','远程服务器名或ip地址'  
exec   sp_addlinkedsrvlogin   'srv_lnk','false',null,'用户名','密码'  
go  
   
--查询示例  
select    from   srv_lnk.数据库名.dbo.表名  
   
   
--以后不再使用时删除链接服务器  
exec   sp_dropserver   'srv_lnk','droplogins'  
go

2、方法二:

--如果只是临时访问,可以直接用openrowset  
--查询示例  
  select    from   openrowset('SQLOLEDB'  
  ,'sql服务器名';'用户名';'密码'  
  ,数据库名.dbo.表名)  

但是默认情况下会报错如下:
SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的STATEMENT'OpenRowset/OpenDatasource' 的访问,因为此组件已作为此服务器安全配置的一部分而被关闭。系统管理员可以通过使用 sp_configure 启用 'Ad Hoc Distributed Queries'.有关启用 'Ad Hoc Distributed Queries' 的详细信息...

解决方法:

启用Ad Hoc Distributed Queries:

exec sp_configure 'show advanced options',1
go
reconfigure
go
exec sp_configure 'Ad Hoc Distributed Queries',1
go
reconfigure
go

使用完成后,关闭Ad Hoc Distributed Queries:

exec sp_configure 'Ad Hoc Distributed Queries',0
go
reconfigure
go
exec sp_configure 'show advanced options',0
go
reconfigure
go

要是远程的话,则需要启动远程服务器的MSDTC服务

--启动远程服务器的MSDTC服务  
  exec   master..xp_cmdshell   'isql   /S"xz"   /U"sa"   /P""   /q"exec  master..xp_cmdshell   ''net   start   msdtc'',no_output"',no_output  
   
--启动本机的MSDTC服务  
exec   master..xp_cmdshell   'net   start   msdtc',no_output

 

----方法3

数据库1:AAA

数据库2:BBB

数据库名和表名之间放两个点

select * from [AAA]..TableA a inner join [BBB]..TableB b on a.AcountID = b.ClientID

注意:必须是单个Sql实例!

原创粉丝点击