我有一个表the_tbl
,其列SQL Statement
,每行有不同的SQL查询。
******************************************************
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语句吗?这样它就不会重复已经执行过的同一个查询?
答案 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