我该如何将动态SQL插入临时表?

5

我有一个动态查询,如何将其结果插入临时表中?这个查询的结果显示了(1000 行受影响),但有没有办法将这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;

https://dev59.com/lXRB5IYBdhLWcg3wWF8H#1228165 以及它下面的答案。答案:要在Java中连接字符串,您可以使用"+"运算符或String.format()方法。使用“+”运算符:String str1 = "Hello"; String str2 = "World"; String str3 = str1 + ", " + str2 + "!"; System.out.println(str3); //输出:Hello, World!使用String.format()方法:String str1 = "Hello"; String str2 = "World"; String str3 = String.format("%s, %s!", str1, str2); System.out.println(str3); //输出:Hello, World! - S3S
2
如果您想使用临时表,您需要在动态SQL之外创建临时表。 - EMUEVIL
如果我有Microsoft SQL Server 2012 (SP3) (KB3072779) - 11.0.6020.0 (X64) Oct 20 2015 15:36:27 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ),我的“提供程序名称”会是什么? - Serdia
2个回答

10
我运行了这段代码,它返回了我创建的测试行。
declare @query nvarchar(100)
set @query = N'select * into ##TMPTblTest from tblTest'

exec sp_executesql @query;

select * from ##TMPTblTest

您正在使用全局临时表。如果对其进行选择操作,我认为它将起作用。


运行正常!谢谢。 - Serdia

7
你可以在动态 SQL 外部声明临时表结构,这样就避免使用全局临时表。
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
以上为ID列表,包括编号和对应的ID值。

这是一个直接证明临时表可以从同一脚本中的动态SQL接收数据的方法。很好的方式,添加了第二种从动态SQL插入的方法。(在其上方添加了注释,希望能为未来的观众澄清。) - yeOldeDataSmythe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接