Insert result of executing dynamic query into a ta

2019-04-07 13:59发布

问题:

I have a dynamic query @strQuery which on executing gives a result with lots of column. I want to insert the result from this dynamic query into a temporary table . I am doing this because I want to perform some filtering on the temporary table and get required result .

A similar question was asked on previous thread HERE in which a temporary table is created first and then data inserted using INSERT INTO.

I want to avoid this step due to long list of columns and also the datatypes of fields is not known to me.

select * into #tmh from
exec(@strQuery)

Error Message

Incorrect syntax near the keyword 'exec'.

How to do this ? Is it possible to be done in this way ? If not , please specify some other alternative to get store the result on executing dynamic query into a table. Thanks.

回答1:

I have faced this situation before and here is what I did:

DECLARE @strQuery nVarchar(100)

SET @strQuery='SELECT * into [tempdb].[dbo].[temptable] FROM YourTable'

EXECUTE sp_executesql @strQuery

SELECT * FROM [tempdb].[dbo].[temptable]

DROP TABLE [tempdb].[dbo].[temptable]

It works fine. Don't ask me why a FQ table name and not #temptable. I have no idea. It does not work. The only way I could get it working was using [tempdb].[dbo].[temptable]



回答2:

proceed like this

select t1.name,t1.lastname from(select * from table)t1.

where "select * from table" is your dyanmic query. which will return result which you can use as temp table t1 as given in example .



回答3:

You can use variables in your current execution context, set by the Dynamic SQL with the OUTPUT option. Sample code below.

DECLARE @Amount AS MONEY
DECLARE   @SQL AS NVARCHAR(1000)
SET @Amount = NULL 
SET @SQL = ('SELECT @amt=100' )
EXECUTE   sp_executeSQL @SQL, N'@amt MONEY OUTPUT', @amt=@Amount OUTPUT
SELECT  @Amount


回答4:

Yes you can make a new dynamic query containing the original query with the insert like this:

declare @strNewQuery varchar(max)
set @strNewQuery ='select * into #tmh from ('+@strQuery+') as t'
exec(@strNewQuery)


回答5:

I used this to work around - with out dynamic query

This uses a table variable to receive data to procedure

Even joins can be applied to it

select * into #itemPhantom from @tbl_items_upload

select * from #itemPhantom

select #itemPhantom.itemreference from #itemPhantom  left join phantom on phantom.name=#itemPhantom.PhantomName