我有一个包含选择语句列表的表:
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(。
只需像这样使用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);
在表上使用光标,并以动态 t-sql 的形式执行,并使用 SQL 语句在每个值的开头添加insert into
。
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;