跨库查询(OpenDataSource)与链接服务器(Linking Server)

一:跨库查询

Openrowset/opendatasource() is an ad-hoc method to access remote server's data. So, if you only need to access the remote server's data once and you do not to persist the connection info, this would be the right choice. Otherwise, you should create a linked server.

开启'Ad Hoc Distributed Queries'

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

关闭'Ad Hoc Distributed Queries'

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

SQL如下:

select * from [User] a 
  left join OPENDATASOURCE( 
         'SQLOLEDB', 
         'Data Source=192.168.1.20;User ID=sa;Password=yhbj' 
         ).Kitty2.dbo.Question b on a.Id = b.UserId

结果:

image

 

二:链接服务器

Linked server is a persistent registration for the remote server. This allows you to define the connection property once and be able to use the server "alias" over and over again.

STEP1:

image

STEP2:

如果是在同一个局域网内,不妨直接选中“SQLSERVER”链接,

image

STEP3:

image

STEP4:

image

 

三:OpenDataSource VS Linking Server

有这样一个实例:

using linked server 
SELECT * FROM mylinkedserver.[mydatabase].[dbo].[mytable] 
requires 10s 
but when using 
SELECT * FROM OPENDATASOURCE('SQLNCLI','Data Source=myserver;User ID=sa;Password=xxxxxx').[mydatabase].[dbo].[mytable] 
it lasts for 10 mins and still continue

其它基于LINK SERVER的效率问题的一些描述:

http://www.sql-server-performance.com/2007/linked-server/

 

四:代码实现

static void Main(string[] args) 

    var x = Query("select * from [User] a left join [192.168.1.20].Kitty2.dbo.Question b on a.Id = b.UserId "); 
    Console.WriteLine(x.Tables[0].Rows.Count);

    var y = Query("select * from [User] a" 
                  + " left join OPENDATASOURCE(" 
                  + " 'SQLOLEDB','Data Source=192.168.1.20;User ID=sa;Password=yhbj' " 
                  + " ).Kitty2.dbo.Question b on a.Id = b.UserId "); 
    Console.WriteLine(y.Tables[0].Rows.Count); 
}

private static string connectionString = @"Data Source=192.168.1.19;Initial Catalog=Kitty1;Integrated Security=False;User ID=sa;Password=yhbj;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";

public static DataSet Query(string SQLString) 

    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
        connection.Open(); 
        SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); 
        DataSet ds = new DataSet(); 
        command.Fill(ds, "ds"); 
        return ds; 
    } 
}


本文转自最课程陆敏技博客园博客,原文链接:http://www.cnblogs.com/luminji/p/3445407.html,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值