简体   繁体   中英

Dynamic SQL Query from Function into temp table

Let's say I have an scalar function that returns a query:

CREATE FUNCTION [cimpl].[GetQuery]()
RETURNS NVARCHAR(MAX)
AS
BEGIN

    RETURN  'SELECT col1, col2, col3 from dbo.table1 '
END

this is an example but it something already like this and the GetQuery function can be any other function with different columns, my goal is to put this result into a temp table from inside a different sp.

With this result, I need to put it inside a temp table, my problem is that I don't want to create a temp table because I don't know which are the expected columns so I need to create it on the flight. One thing, I cannot modify the function

SELECT * 
INTO #temp
FROM cimpl.GetQuery()

SQL Server does not make it easy to work with tables that have unspecified columns. If you knew the columns you could do:

create table #temp ( . . . );
declare @sql nvarchar(max);

select @sql = getquery();
insert into #temp (. . . )
    exec(@sql);

But you don't.

I don't recommend what I'm about to suggest, but you can sort of get this to work. I suspect that there are better ways to solve your real problem, but you haven't asked a question that describes that.

The idea is the following:

  • Use into
  • Don't use a temporary table

Assuming your query has no subqueries in the select , you can do:

select @sql = getquery();

set @sql = stuff(@sql, charindex('FROM ', @sql) - 5, 0, ' INTO _temp_table ');

exec(@sql);

This isn't a temporary table, so you need to remember to drop it later in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM