避免建立表的状况下,执行存储过程插入临时表

通常状况下,咱们要将存储过程的结果集插入临时表的时候,须要如下步骤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,来返回结果行给客户端

相关文章
相关标签/搜索