将exec sql的结果存储在临时表中

时间:2018-01-18 22:17:47

标签: sql sql-server tsql

我有一段运行良好的代码,但我想将Exec(@sql)的输出存储到临时表中。

Declare @Date date
Declare @sql nvarchar(max)
Set @Date= DATEADD(DD, DATEDIFF(DY, 0, GETDATE()), -1)
Set @sql='SELECT * 
FROM OPENROWSET(
           ''SQLNCLI'',
           ''Server=Servername;Trusted_Connection=yes;'',
           ''select * from servername.dbo where 
                  cast( (substring(cast(convert(date,createtsdt) as char (10)),1,4) + substring(cast(convert(date,createtsdt) as char (10)),6,2) 
                   +substring(cast(convert(date,createtsdt) as char (10)),9,2) ) as varchar(8) ) >=' + 
                    cast( (substring(cast(convert(date,@Date) as char (10)),1,4) + substring(cast(convert(date,@Date) as char (10)),6,2) 
                   +substring(cast(convert(date,@Date) as char (10)),9,2) ) as varchar(8) ) + ''')'

Exec @sql1

如何将exec @sql1生成的输出存储到临时表

2 个答案:

答案 0 :(得分:1)

您可以创建表格并使用insert . . . exec

类似的东西:

create table #t as (
    id int identity(1, 1) primary key
    createtsdt date
);

insert into #t (createtsdt)
    exec(@sql1);

答案 1 :(得分:0)

您可以通过添加INSERT INTO来解决此问题:

Set @sql= N'INSERT INTO #TEMP (Col1, ...) SELECT Col1, ... 
FROM OPENROWSET(....