避免建立表的狀況下,執行存儲過程插入臨時表

通常狀況下,咱們要將存儲過程的結果集插入臨時表的時候,須要如下步驟sql

Create table #temptable(column)。。。。數據庫

insert into #temptableapp

exec yourspide

這樣作起來很煩瑣,若是結果集有不少列,那就更痛苦了。sqlserver

今天介紹一個靈活的辦法spa

腳本以下:code

 exec sp_configure 'show advanced options',1
reconfigure
exec sp_configure 'Ad Hoc Distributed Queries',1
reconfigure
--SET FMTONLY OFF
 
 IF OBJECT_ID('tempdb..#t') IS NOT NULL

    DROP TABLE #t

GO

SELECT *  

INTO #t

FROM OPENROWSET( 'SQLNCLI10','DRIVER={SQL Server};SERVER=dbserver;UID=userid;PWD=password;Initial Catalog=DBTrain',' exec DBTrain..sp_depends multiresult')

SELECT * FROM #t

SQLNCLI在SqlServer2005以上才能使用
sqlserver 2008 的 provider 爲:SQL Server Native Client 10.0 OLE DB Provider
<標準鏈接>字符串爲:Provider=SQLNCLI10;Server=myServerAddress;Database=myDataBase;Uid=myUsername; Pwd=myPassword;
<信任鏈接>字符串爲:Provider=SQLNCLI10;Server=myServerAddress;Database=myDataBase; Trusted_Connection=yes;
鏈接到數據庫的具體實例:Provider=SQLNCLI10;Server=myServerName\theInstanceName;Database=myDataBase; Trusted_Connection=yes;

這樣就能夠將結果集插入到臨時表中,而不須要新建立表結構。server

到這裏尚未完,若是咱們執行如下的語句blog

EXEC ('DBCC IND(DBTrain,Department8,-1)')字符串

若是在Transact-SQL 中執行是正常的,可是放到OPENROWSET中,

則會出現錯誤提示:

Msg 7357, Level 16, State 2, Line 2
Cannot process the object "  EXEC ('DBCC IND(DBTrain,Department8,-1)')". The OLE DB provider "SQLNCLI10" for linked server "(null)" indicates that either the object has no columns or the current user does not have permissions on that object.

要解決這個問題就要用到

SET FMTONLY OFF;

SELECT *  

INTO #t

FROM OPENROWSET( 'SQLNCLI10','DRIVER={SQL Server};SERVER=shasapp62;UID=sasalesbudget;PWD=Sanofi2011;Initial Catalog=DBTrain',' SET FMTONLY OFF; EXEC (''DBCC IND(DBTrain,Department8,-1)'')')

當 SET FMTONLY 爲 ON 時,將不對行進行處理,也不將行做爲請求的結果發送到客戶端,只返回描述列信息的元數據;

在OLE DB Source中,須要顯式的設置SET FMTONLY = OFF,來返回結果行給客戶端

相關文章
相關標籤/搜索