执行存储在表列中的不同查询

时间:2018-06-11 15:00:25

标签: sql sql-server sql-server-2008 tsql database-cursor

我有一个表the_tbl,其列SQL Statement,每行有不同的SQL查询。

the_tbl: table described here

******************************************************
Col1 ||  Col2  || SQL_Statement
******************************************************
A    |     1   |  SELECT * FROM the_tbl
B    |     2   |  SELECT Col 2 from the_tbl
C    |     3   |  SELECT * FROM the_tbl
****************************************************** 

我正在使用游标迭代每一行并打印每个语句的结果。

DECLARE @execute_queries nvarchar(max)  

DECLARE my_cur CURSOR FOR 
SELECT the_tbl.SQL_Statement FROM the_tbl;

OPEN my_cur;
FETCH NEXT FROM my_cur INTO @execute_queries;

WHILE (@@FETCH_STATUS = 0)
BEGIN
    EXECUTE(@execute_queries) 
    FETCH NEXT FROM my_cur INTO @execute_queries
END;
CLOSE my_cur

我希望以这样一种方式执行游标:如果已经执行了SQL查询,那么就不应该重复它。

例如,如果你看第1行和第1行3在the_tbl上,重复查询SELECT * FROM the_tbl。我怎么能阻止这种情况发生? 我可以在Cursor中使用If语句吗?这样它就不会重复已经执行过的同一个查询?

2 个答案:

答案 0 :(得分:2)

这是一种非光标方式

See working demo

declare @execute_queries nvarchar(max) 
select @execute_queries=stuff((select distinct ';'
+ the_tbl.SQL_Statement FROM the_tbl 
for xml path('')),1,1,'')
execute( @execute_queries)

答案 1 :(得分:1)

使用GROUP BY语句删除重复项:

SELECT the_tbl.SQL_Statement FROM the_tbl GROUP BY the_tbl.SQL_Statement;

所以你的代码应该是:

DECLARE @execute_queries nvarchar(max)  

DECLARE my_cur CURSOR FOR 
SELECT the_tbl.SQL_Statement FROM the_tbl GROUP BY the_tbl.SQL_Statement; --Added GROUP BY

OPEN my_cur;
FETCH NEXT FROM my_cur INTO @execute_queries;

WHILE (@@FETCH_STATUS = 0)
BEGIN
    EXECUTE(@execute_queries) 
    FETCH NEXT FROM my_cur INTO @execute_queries
END;
CLOSE my_cur
DEALLOCATE my_cur

正如评论中所指出的,您可以使用DISTINCT获得相同的结果:

DECLARE @execute_queries nvarchar(max)  

DECLARE my_cur CURSOR FOR 
SELECT DISTINCT the_tbl.SQL_Statement FROM the_tbl; --Added DISTINCT

OPEN my_cur;
FETCH NEXT FROM my_cur INTO @execute_queries;

WHILE (@@FETCH_STATUS = 0)
BEGIN
    EXECUTE(@execute_queries) 
    FETCH NEXT FROM my_cur INTO @execute_queries
END;
CLOSE my_cur
DEALLOCATE my_cur