條件:有數(shù)據(jù)庫 test1、數(shù)據(jù)庫 test2。test1中有表 table1、table2;test2 中有表 table1。三個表的字段為:id、xingming、shijian、shuliang。
一、跨數(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'
注意事項:dbo 一定要有,不可以沒有
二、跨表:(在數(shù)據(jù)庫test1內(nèi))
SELECT * FROM table1 where xingming='a'
UNION all
SELECT * FROM table2 where xingming='a'
這是 UNION ALL 的作用。
如果上面沒有看懂,先建好上面的數(shù)據(jù)庫和表,下面有個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" '跨庫時,數(shù)據(jù)庫名不必指定,如: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%>
<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>
該文章在 2011/7/1 9:52:22 編輯過