如何将动态 sql 插入临时 table?
How can I insert dynamic sql into temp table?
我有这个动态查询,如何将它的结果插入临时 Table?
此查询的结果显示 (1000 row(s) affected)
但是有没有机会在临时 table 中转储这 1000 行?
类似的东西:
INSERT INTO #TempTable
EXEC(@query)
这是我的查询
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT ',' + QUOTENAME(c.locationCode)
FROM Catalytic_vw_LocationCodeByLine c WHERE c.linename ='wind' order by c.CompanyName, c.LocationCode
FOR XML PATH('')),1,1,'')
set @query =
'select * into ##Temp
from
(SELECT QUOTEGUID as qguid, ' + @cols + ' from
(
select
QuoteGUID,
LocationCode,
LineName,
LineGUID
from Catalytic_vw_PolicyLocationCode
) x
pivot
(
max(locationCode)
for locationCode in (' + @cols + ')
)p)x'
EXEC sp_executesql @query;
我 运行 这段代码,它返回了我创建的测试行。
declare @query nvarchar(100)
set @query = N'select * into ##TMPTblTest from tblTest'
exec sp_executesql @query;
select * from ##TMPTblTest
您正在使用全局临时文件 table。如果你在上面做一个select,我认为它会起作用。
您可以在动态 sql 之外声明临时 table 结构,然后避免使用全局临时 table
if object_id('tempdb..#t1') is not null drop table #t1
create table #t1(ID int)
declare @s varchar(max)
set @s='insert into #t1(ID)select number from master.dbo.spt_values where type=''P'' and number<10'
exec(@s)
insert into #t1(id)
exec('Select 1')
select * from #t1
ID
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
10 9
11 1
我有这个动态查询,如何将它的结果插入临时 Table?
此查询的结果显示 (1000 row(s) affected)
但是有没有机会在临时 table 中转储这 1000 行?
类似的东西:
INSERT INTO #TempTable
EXEC(@query)
这是我的查询
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT ',' + QUOTENAME(c.locationCode)
FROM Catalytic_vw_LocationCodeByLine c WHERE c.linename ='wind' order by c.CompanyName, c.LocationCode
FOR XML PATH('')),1,1,'')
set @query =
'select * into ##Temp
from
(SELECT QUOTEGUID as qguid, ' + @cols + ' from
(
select
QuoteGUID,
LocationCode,
LineName,
LineGUID
from Catalytic_vw_PolicyLocationCode
) x
pivot
(
max(locationCode)
for locationCode in (' + @cols + ')
)p)x'
EXEC sp_executesql @query;
我 运行 这段代码,它返回了我创建的测试行。
declare @query nvarchar(100)
set @query = N'select * into ##TMPTblTest from tblTest'
exec sp_executesql @query;
select * from ##TMPTblTest
您正在使用全局临时文件 table。如果你在上面做一个select,我认为它会起作用。
您可以在动态 sql 之外声明临时 table 结构,然后避免使用全局临时 table
if object_id('tempdb..#t1') is not null drop table #t1
create table #t1(ID int)
declare @s varchar(max)
set @s='insert into #t1(ID)select number from master.dbo.spt_values where type=''P'' and number<10'
exec(@s)
insert into #t1(id)
exec('Select 1')
select * from #t1
ID 1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 9 11 1