1. 程式人生 > >SqlServer 連線字串不使用資料庫名 實現跨庫查詢

SqlServer 連線字串不使用資料庫名 實現跨庫查詢

此次運用需要在同一伺服器下,在一個庫中SQL查詢一組資料,作為引數提交到一個另一個庫的函式中進行計算,以前沒玩過,問了下度娘,未得到可用結果,遂根據查到的零星資訊猜想,取消連線字串裡面的庫名稱試試能不能同時操作多個庫,經測試,順利一次通過執行成功!詳見以下程式碼(以ASP為例):

    Set conn = Server.CreateObject("ADODB.Connection")
    SET Rs = Server.CreateObject("ADODB.Recordset")
    connstr= "Provider=SQLoledb;data source=.;UID=sa;PWD=youpassword;"  '不使用Initial Catalog=DBname"          
    conn.Open connstr
    sql="SELECT * FROM [DBname].[dbo].[TableName] where StationCode ='條件' " 
	rs.Open sql, conn ,1
	If Rs.eof And Rs.bof Then	
		Response.write  "查詢 資料錯誤!
" SID="" else Response.write "SO2:" & rs.Fields("SO2").value & "
" end if CloseDB 2 sql="DECLARE @SO2_data decimal(20,10),@NO2_data decimal(20,10),@PM10_data decimal(20,10),@CO_data decimal(20,10),@O3_1h_data decimal(20,10),@O3_8h_data decimal(20,10),@PM25_data decimal(20,10),@des varchar(100),@PrimaryPollutant varchar(30),@AQI varchar(10);SELECT @CO_data=convert(decimal(20,10),[CO_24h]),@NO2_data=convert(decimal(20,10),[NO2_24h]),@O3_1h_data=convert(decimal(20,10),[O3_24h]),@O3_8h_data=convert(decimal(20,10),[O3_8h]),@PM10_data=convert(decimal(20,10),[PM10_24h]),@PM25_data=convert(decimal(20,10),[PM2_5_24h]),@SO2_data=convert(decimal(20,10),[SO2_24h]) FROM [ProvincePublishV2].[dbo].[AQIDataPublishLive] where StationCode ='1004A';set @des='PrimaryPollutant';SELECT @PrimaryPollutant=[EnvDataProvince].[dbo].[fn_AQI_Publish] (@SO2_data,@NO2_data,@PM10_data,@CO_data,@O3_1h_data,@O3_8h_data,@PM25_data,@des);set @des='AQI';SELECT @AQI=[EnvDataProvince].[dbo].[fn_AQI_Publish] (@SO2_data,@NO2_data,@PM10_data,@CO_data,@O3_1h_data,@O3_8h_data,@PM25_data,@des);SELECT @PrimaryPollutant as 'PrimaryPollutant' ,@AQI as 'AQI';" rs.Open sql, conn ,1 If Rs.eof And Rs.bof Then Response.write "查詢AQI錯誤!
" SID="" else Response.write "PrimaryPollutant:" & rs.Fields("PrimaryPollutant").value & ", AQI:" & rs.Fields("AQI").value end if CloseDB 1 '----附關閉資料連線子程式-------------------------------- Public Sub CloseDB(allClose) '1 ,AllClose & Nothing '0 ,AllClose '2 ,RS Close '3 ,RS Close & Nothing On Error Resume Next If allClose = 1 Then If Not RS Is Nothing Then If RS.State = 1 Then RS.Close Set RS = Nothing '---------------- End If If Not conn Is Nothing Then If conn.State = 1 Then conn.Close Set conn = Nothing '--------------------- End If ElseIf allClose = 0 Then If Not RS Is Nothing Then If RS.State = 1 Then RS.Close End If If Not conn Is Nothing Then If conn.State = 1 Then conn.Close End If ElseIf allClose = 2 Then If Not RS Is Nothing Then If RS.State = 1 Then RS.Close End If ElseIf allClose = 3 Then If Not RS Is Nothing Then If RS.State = 1 Then RS.Close Set RS = Nothing '-------------- End If End If 'Response.write "function1 CONN closeed!" End Sub

裡面的 DBname 即為正常連線時需要寫在 Initial Catalog= 的庫名,這裡不寫庫名的話,在SQL語句中就必須帶上庫名加上[dbo] 標識再加上表名稱來定位到資料表,切記!

即  [DBname].[dbo].[TableName] 

這樣,更換了  DBname  後 就可以實現在多個庫之間自由查詢了。

此記.