Pages - Menu

2017年6月29日 星期四

SQL跨伺服器查詢

今天剛好碰到一個問題,

該料號失效了,但在其他伺服器仍尚未失效…

所以只好開始清查到底有哪些沒改到。

但又好懶得用excel比對,只好下指令查詢了。


程式如下

exec sp_configure 'show advanced options',1
reconfigure
exec sp_configure 'Ad Hoc Distributed Queries',1
reconfigure
--使用完畢後,記得一定要要關閉它,因為這是一個安全隱患,切記執行下面的SQL語句
exec sp_configure 'Ad Hoc Distributed Queries',0
reconfigure
exec sp_configure 'show advanced options',0
reconfigure

select  a.item_no,a.exp_dt,b.ITEM_no,b.EXP_DT from
   OPENROWSET('SQLNCLI', 'Server=192.168.x.x;UID=xxxx;PWD=xxxxx;',
'select item_no,exp_dt from mst_femco.dbo.item where exp_dt is not null') as a ,
item b
where a.item_no=b.ITEM_NO
and b.EXP_DT is null

主要關鍵字是OPENROWSET,要注意的是,不確定此帳號登入會切到哪個資料庫

所以查詢的時候最好在from後面接上資料庫名稱再寫table

沒有留言:

張貼留言