在表SQL Server中执行已保存的查询

时间:2017-08-21 07:31:21

标签: sql sql-server

我有一个包含select语句列表的表:

 query
 ----------------------------
 Select Max(acc),Min(acc)  from my_table1
 Select Max(acc),Min(acc)  from my_table2
 Select Max(acc),Min(acc)  from my_table3
 .......

我想在表中执行所有已保存的查询,并将所有结果保存在新表中。因为所有结果都应匹配(MAX和MIN)。

2 个答案:

答案 0 :(得分:2)

只需使用UNION ALL,就像这样:

declare @sql nvarchar(max);

select 
    @sql = case when @sql is null then '' else @sql + ' union all ' end + query
from 
    t;

insert into destinationTable (max, min)
EXEC sp_executesql (@sql);

答案 1 :(得分:0)

在表上使用游标,并使用SQL语句在每个值的开头添加insert into作为动态t-sql执行。

CREATE TABLE tSELECT 
(
    query VARCHAR(1000)
);
INSERT INTO tselect VALUES ('Select Max(acc),Min(acc)  from my_table1')
CREATE TABLE result (min INT, max int);

BEGIN
    DECLARE @stmt VARCHAR(1000);
    DECLARE db_cursor CURSOR FOR  SELECT * FROM tselect;
    OPEN db_cursor  FETCH NEXT FROM db_cursor INTO @stmt
    WHILE @@FETCH_STATUS = 0   
    BEGIN   
           EXEC('insert into result ' + @stmt);

           FETCH NEXT FROM db_cursor INTO @stmt   
    END   

    CLOSE db_cursor   
    DEALLOCATE db_cursor    
END;