新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
MSSQL數(shù)據(jù)庫跨表和跨數(shù)據(jù)庫查詢方法簡介
本文主要介紹MSSQL數(shù)據(jù)庫跨表和跨數(shù)據(jù)庫查詢的方法,我們假設(shè)有數(shù)據(jù)庫test1和數(shù)據(jù)庫test2。其中test1中有表 table1、table2;test2 中有表 table1。三個表的字段都為為:id、xingming、shijian、shuliang。接下來我們就以上面的條件為例來介紹跨數(shù)據(jù)庫查詢和跨表查詢的方法。

一、跨數(shù)據(jù)庫
(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'
注意事項(xiàng):dbo一定要有,不可以沒有。
二、跨表
跨表查詢我們在數(shù)據(jù)庫test1內(nèi)實(shí)現(xiàn),執(zhí)行以下的代碼:
- SELECT * FROM table1 where xingming='a'
- UNION all
- SELECT * FROM table2 where xingming='a'
這就是UNION ALL 的作用。
如果上面沒有看懂,先建好上面的數(shù)據(jù)庫和表,下面有個asp實(shí)例,照抄就可以了。
文件名:unionall.asp
- <%sqlStr="provider=sqloledb;data source=127.0.0.1;uid=sa;pwd=;database=test1" '跨庫時,數(shù)據(jù)庫名不必指定,如: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%>
<%if not rs.eof then id xingming shijian shuliang - do while not rs.eof%>
<%rs.movenext <%=rs("id")%> <%=rs("xingming")%> <%=rs("shijian")%> <%=rs("shuliang")%> - loop
- end if
- rs.close
- set rs=nothing
- conn.close
- set conn=nothing%>
關(guān)于MSSQL數(shù)據(jù)庫跨數(shù)據(jù)庫查詢和跨表查詢的方法就介紹到這里,如果您有更好的方法,歡迎您與我們分享,謝謝!
網(wǎng)頁題目:MSSQL數(shù)據(jù)庫跨表和跨數(shù)據(jù)庫查詢方法簡介
分享鏈接:http://www.dlmjj.cn/article/djoojjg.html


咨詢
建站咨詢
