隐藏

MSSQL数据库跨表和跨数据库查询方法简介

发布:2014/12/16 0:15:14作者:管理员 来源:本站 浏览次数:1232

本文主要介绍MSSQL数据库跨表和跨数据库查 询的方法,我们假设有数据库test1和数据库test2。其中test1中有表 table1、table2;test2 中有表 table1。三个表的字段都为为:id、xingming、shijian、shuliang。接下来我们就以上面的条件为例来介绍跨数据库查询和跨表 查询的方法。

一、跨数据库

(1)原始:

  1. SELECT *  

  2.   FROM OPENROWSET('sqloledb',  

  3.         'DRIVER={SQL Server};SERVER=127.0.0.1;UID=sa;PWD=ccds',    

  4.         test1.dbo.table1)  where xingming='a' 

  5.   UNION   all    

  6. SELECT *  

  7.   FROM OPENROWSET('sqloledb',  

  8.         'DRIVER={SQL Server};SERVER=127.0.0.1;UID=sa;PWD=ccds',    

  9.         test2.dbo.table1)  where xingming='a'

(2)简化:

  1. SELECT * FROM test1.dbo.table1  where xingming='a' 

  2.   UNION   all    

  3. SELECT * FROM test2.dbo.table1  where xingming='a'

注意事项:dbo 一定要有,不可以没有。

二、跨表

跨表查询我们在数据库test1内实现,执行以下的代码:

  1. SELECT * FROM table1  where xingming='a' 

  2.   UNION   all    

  3. SELECT * FROM table2  where xingming='a'

这就是UNION ALL 的作用。

如果上面没有看懂,先建好上面的数据库和表,下面有个asp实例,照抄就可以了。

文件名:unionall.asp

  1. <html> 

  2. <head> 

  3. <meta http-equiv="Content-Language" content="zh-cn"> 

  4. </head> 

  5. <body> 

  6. <%sqlStr="provider=sqloledb;data source=127.0.0.1;uid=sa;pwd=;database=test1"    '跨库时,数据库名不必指定,如:database=  

  7. set conn=server.createObject("adodb.connection")  

  8. conn.open sqlStr  

  9. set rs=server.createObject("adodb.Recordset")  

  10. sql="   SELECT * " 

  11. sqlsql=sql&" FROM test1.dbo.table1  where xingming='a' "  

  12. sqlsql=sql&" UNION all "  

  13. sqlsql=sql&" SELECT * "  

  14. sqlsql=sql&" FROM test2.dbo.table1  where xingming='a'"  

  15. rs.open sql,conn,1%> 

  16. <div align="center"> 

  17.  <table border="1" style="border-collapse: collapse" width="388" bordercolor="#0000FF" id="table1"> 

  18.   <tr> 

  19.    <td height="28" bgcolor="#CCCCCC" align="center"><b>id</b></td> 

  20.    <td width="135" height="28" bgcolor="#CCCCCC" align="center"><b>xingming</b></td> 

  21.    <td width="109" height="28" bgcolor="#CCCCCC" align="center"><b>shijian</b></td> 

  22.    <td width="89" height="28" bgcolor="#CCCCCC" align="center"><b>shuliang</b></td> 

  23.   </tr><%if not rs.eof then  

  24.   do while not rs.eof%> 

  25.  <tr> 

  26.    <td height="28" align="center"><%=rs("id")%></td> 

  27.    <td width="135" height="28" align="center"><%=rs("xingming")%></td> 

  28.    <td width="109" height="28" align="center"><%=rs("shijian")%></td> 

  29.    <td width="89" height="28" align="center"><%=rs("shuliang")%></td> 

  30.   </tr><%rs.movenext  

  31.   loop  

  32.   end if  

  33. rs.close  

  34. set rs=nothing 

  35. conn.close  

  36. set conn=nothing%> 

  37.  </table> 

  38. </div> 

  39. </body> 

  40. </html>

关于MSSQL数据库跨数据库查询和跨表查询的方法就介绍到这里,如果您有更好的方法,欢迎您与我们分享,谢谢!