简体   繁体   English

从函数到临时表的动态SQL查询

[英]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. 这是一个示例,但是已经有点像这样了,GetQuery函数可以是其他任何具有不同列的函数,我的目标是将结果从另一个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. SQL Server无法轻松处理具有未指定列的表。 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 使用into
  • Don't use a temporary table 不要使用临时表

Assuming your query has no subqueries in the select , you can do: 假设您的查询在select没有子查询,则可以执行以下操作:

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. 这不是临时表,因此您需要记住稍后将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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