MSSQL数据库跨表和跨数据库查询方法简(转)

本文深入探讨了在MSSQL环境下进行跨数据库和跨表查询的方法,包括使用OPENROWSET函数实现跨数据库查询及UNION ALL操作进行跨表查询,并提供了ASP实例代码以辅助理解。

(注:本文转自http://zhidao.zgsj.com/article/5/2011715100803.shtml

我们假设有数据库test1和数据库test2。其中test1中有表 table1、table2;test2 中有表 table1。三个表的字段都为为:id、xingming、shijian、shuliang。接下来我们就以上面的条件为例来介绍跨数据库查询和跨表查询的方法。
一、MSSQL跨数据库查询
(1)原始:
SELECT * 
  FROM OPENROWSET('sqloledb', 
 'DRIVER={SQL Server};SERVER=127.0.0.1;UID=sa;PWD=ccds',
 test1.dbo.table1)  where xingming='a'
  UNION   all
SELECT * 
  FROM OPENROWSET('sqloledb', 
 'DRIVER={SQL Server};SERVER=127.0.0.1;UID=sa;PWD=ccds',
 test2.dbo.table1)  where xingming='a'

(2)简化:
SELECT * FROM test1.dbo.table1  where xingming='a'
  UNION   all
SELECT * FROM test2.dbo.table1  where xingming='a'
  注意事项:dbo 一定要有,不可以没有。

二、MSSQL跨表查询
  跨表查询我们在数据库test1内实现,执行以下的代码:
SELECT * FROM table1  where xingming='a'
  UNION   all
SELECT * FROM table2  where xingming='a'
  这就是UNION ALL 的作用。
  如果上面没有看懂,先建好上面的数据库和表,下面有个asp实例,照抄就可以了。
  文件名:unionall.asp
<html>
<head>
<meta http-equiv="Content-Language" content="zh-cn">
</head>
<body>
<%sqlStr="provider=sqloledb;data source=127.0.0.1;uid=sa;pwd=;database=test1"'跨库时,数据库名不必指定,如:database= 
set conn=server.createObject("adodb.connection") 
conn.open sqlStr 
set rs=server.createObject("adodb.Recordset") 
sql="   SELECT * "
sqlsql=sql&" FROM test1.dbo.table1  where xingming='a' " 
sqlsql=sql&" UNION all " 
sqlsql=sql&" SELECT * " 
sqlsql=sql&" FROM test2.dbo.table1  where xingming='a'" 
rs.open sql,conn,1%>
<div align="center">
 <table border="1" style="border-collapse: collapse" width="388" bordercolor="#0000FF" id="table1">
  <tr>
<td height="28" bgcolor="#CCCCCC" align="center"><b>id</b></td>
<td width="135" height="28" bgcolor="#CCCCCC" align="center"><b>xingming</b></td>
<td width="109" height="28" bgcolor="#CCCCCC" align="center"><b>shijian</b></td>
<td width="89" height="28" bgcolor="#CCCCCC" align="center"><b>shuliang</b></td>
  </tr><%if not rs.eof then 
  do while not rs.eof%>
 <tr>
<td height="28" align="center"><%=rs("id")%></td>
<td width="135" height="28" align="center"><%=rs("xingming")%></td>
<td width="109" height="28" align="center"><%=rs("shijian")%></td>
<td width="89" height="28" align="center"><%=rs("shuliang")%></td>
  </tr><%rs.movenext 
  loop 
  end if 
rs.close 
set rs=nothing
conn.close 
set conn=nothing%>
 </table>
</div>
</body>
</html>

转载于:https://www.cnblogs.com/xingluzhe/archive/2012/02/01/2334311.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值