我有一个包含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)。
答案 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;