MSSQL資料庫 跨表 和 跨資料庫 查詢方法

2021-05-24 04:43:59 字數 1853 閱讀 2994

mssql資料庫 跨表 和 跨資料庫 查詢方法

條件:有資料庫 test1、資料庫 test2。test1中有表 table1、table2;test2 中有表 table1。三個表的字段為:id、xingming、shijian、shuliang。

一、跨資料庫:

(1)原始:

select *

from openrowset('sqloledb',

'driver=;server=127.0.0.1;uid=sa;pwd=ccds',  

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

union   all  

select *

from openrowset('sqloledb',

'driver=;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 一定要有,不可以沒有

二、跨表:(在資料庫test1內)

select * from table1  where xingming='a'

union   all  

select * from table2  where xingming='a'

這是 union all 的作用。

如果上面沒有看懂,先建好上面的資料庫和表,下面有個asp例項,照抄就可以了。

檔名:unionall.asp

<%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 * "

sql=sql&" from test1.dbo.table1  where xingming='a' "

sql=sql&" union all "

sql=sql&" select * "

sql=sql&" from test2.dbo.table1  where xingming='a'"

rs.open sql,conn,1%>

id

xingming

shijian

shuliang

<%if not rs.eof then

do while not rs.eof%>

<%=rs("id")%>

<%=rs("xingming")%>

<%=rs("shijian")%>

<%=rs("shuliang")%>

<%rs.movenext

loop

end if

rs.close

set rs=nothing

conn.close

set conn=nothing%>

再看不懂,買塊豆腐自殺撞死。

MsSQL跨資料庫同步資料

set quoted identifier on goset ansi nulls on goexec p utils synchronousmssqldata srv lnk yurun yurun.dbo.rainview st pptn r stcd,tm,r5 tm tm where dat...

資料庫 mysql 跨庫訪問 資料庫跨庫訪問問題

sql server中的所有權鏈及其問題 沒有多少朋友對所有權鏈真的理解的。我自己有時候經常回過來看看這些資料,覺得還是很有意思的。下面的內容摘自微軟文件,介紹得比較好 簡而言之 1.如果在同乙個資料庫中,只要兩個物件的所有者是一樣的,那麼他們之間的訪問是不檢查訪問者身份的。例如乙個檢視和乙個表是屬...

跨資料庫引擎 資料庫查詢

包含訪問 ole db 資料來源中的遠端資料所需的全部連線資訊。當訪問鏈結伺服器中的表時,這種方法是一種替代方法,並且是一種使用 ole db 連線並訪問遠端資料的一次性的 特殊的方法。可以在查詢的 from 子句中像引用表名那樣引用 openrowset 函式。依據 ole db 提供程式的能力,...