sql server中提供很多有用的系統(tǒng)存儲(chǔ)過程,但是我們都知道,存儲(chǔ)過程的結(jié)果集是不能用select來過濾的,也就是說select * from sp_who where [dbname] = ‘xxx’;這樣的語句是執(zhí)行不過。下面介紹兩種方法來解決這個(gè)問題
方法一:使用臨時(shí)表。
首先創(chuàng)建一個(gè)與sp_who相同字段的臨時(shí),然后用insert into 方法賦值,這樣就可以select這個(gè)臨時(shí)表了。具體代碼如下:
create table #TempTable(spid int,ecid int,status varchar(32),loginname varchar(32),hostname varchar(32),blk int,dbname varchar(32),cmd varchar(32),request_id int);
insert into #TempTable
exec sp_who;
select * from #TempTable where [dbname] = ‘master’;
drop table #TempTable
方法二:使用OPENROWSET
代碼如下:
select * from openrowset(‘SQLOLEDB’,’servername’;’userName’;’password’,’sp_who’) where [dbname] = ‘master’;
執(zhí)行上面這個(gè)語句,如果提示:SQL Server 阻止了對組件 ‘Ad Hoc Distributed Queries’ 的 STATEMENT’OpenRowset/OpenDatasource’ 的訪問,因?yàn)榇私M件已作為此服務(wù)器安全配置的一部分而被關(guān)閉。系統(tǒng)管理員可以通過使用 sp_configure 啟用 ‘Ad Hoc Distributed Queries’。有關(guān)啟用 ‘Ad Hoc Distributed Queries’ 的詳細(xì)信息。
說明你沒有配置 ‘Ad Hoc Distributed Queries’ ,按如下方法配置
啟用Ad Hoc Distributed Queries:
exec sp_configure ‘show advanced options’,1
reconfigure
exec sp_configure ‘Ad Hoc Distributed Queries’,1
reconfigure
然后就可以運(yùn)行上面的代碼了。
使用完成后,如果想關(guān)閉Ad Hoc Distributed Queries,執(zhí)行如下代碼:
exec sp_configure ‘Ad Hoc Distributed Queries’,0
reconfigure
exec sp_configure ‘show advanced options’,0
reconfigure