将结果从openrowset方法移动到sql中的Temp表中

时间:2016-03-04 07:49:49

标签: sql-server-2008

使用

DECLARE @testVariable uniqueidentifier; 
SET @testVariable ='c0cad38f-da93-46b5-9f90-ff9eea7dbfd8'; 
DECLARE @qry varchar(2000);



SET @qry = 'SELECT * into #REPORT_1 FROM OPENROWSET
 ( ''SQLNCLI'', 
''Server=localhost;Trusted_Connection=yes;'',
 '' SET FMTONLY OFF EXEC VDMS_DB.dbo.UspRankingOfNonNegotiables4 ''''' + cast(@testVariable as varchar(100)) + ''''''')' 


exec(@qry) 

select * from #REPORT_1

我收到这样的错误

  

无效的对象名称' #REPORT_1'。

请提前感谢我。

2 个答案:

答案 0 :(得分:0)

您可以尝试这样做,删除动态SQL并通过在openrowset语句中直接包含测试变量值使其成为静态。 声明@parameter uniqueidentifier

方法-1

SELECT *
INTO #REPORT_1
FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', ' SET FMTONLY OFF EXEC VDMS_DB.dbo.UspRankingOfNonNegotiables4 @parameter')

SELECT *
FROM #REPORT_1

方法-2

分别创建#Report_1临时表,然后执行Insert to exec ..如下所示。

Create table #REPORT_1
(
col datatype1,
...
...
)

DECLARE @testVariable UNIQUEIDENTIFIER;

SET @testVariable = 'c0cad38f-da93-46b5-9f90-ff9eea7dbfd8';

DECLARE @qry VARCHAR(2000);

SET @qry = 'SELECT * FROM OPENROWSET
 ( ''SQLNCLI'', 
''Server=localhost;Trusted_Connection=yes;'',
 '' SET FMTONLY OFF EXEC VDMS_DB.dbo.UspRankingOfNonNegotiables4 ''''' + cast(@testVariable AS VARCHAR(100)) + ''''''')'

Insert into #REPORT_1 (col,....)
EXEC (@qry)

select *from #REPORT_1

方法-3

DECLARE @testVariable UNIQUEIDENTIFIER;

SET @testVariable = 'c0cad38f-da93-46b5-9f90-ff9eea7dbfd8';

DECLARE @qry VARCHAR(2000);

SET @qry = 'SELECT * FROM OPENROWSET
 ( ''SQLNCLI'', 
''Server=localhost;Trusted_Connection=yes;'',
 '' SET FMTONLY OFF EXEC VDMS_DB.dbo.UspRankingOfNonNegotiables4 ''''' + cast(@testVariable AS VARCHAR(100)) + ''''''')'

SELECT *
INTO #REPORT_1
EXEC (@qry)

SELECT *
FROM #REPORT_1

答案 1 :(得分:0)

  

这有效

select * into #temp_my1 from openrowset
('SQLNCLI','Server=DEV-WKST-136;Trusted_Connection=yes;', 'EXEC performancev3.dbo.usp_testa')

select * from #temp_my1
  

这不起作用......

declare @query nvarchar(4000)
set @query='select * into #temp_my2 from openrowset
(''SQLNCLI'',''Server=DEV-WKST-136;Trusted_Connection=yes;'', ''EXEC performancev3.dbo.usp_testa'')'

exec(@query)

select * from #temp_my2

为什么......?因为exec语句在除当前会话之外的单独会话上下文中执行。