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

一般情况下,我们要将存储过程的结果集插入临时表的时候,需要以下步骤

Create table #temptable(column)。。。。

insert into #temptable

exec yoursp

这样做起来很烦琐,如果结果集有很多列,那就更痛苦了。

今天介绍一个灵活的办法

脚本如下:

 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 heInstanceName;Database=myDataBase; Trusted_Connection=yes;

这样就可以将结果集插入到临时表中,而不需要新创建表结构。

到这里还没有完,如果我们执行以下的语句

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,来返回结果行给客户端

原文地址:https://www.cnblogs.com/wanglg/p/4155522.html