使用 T-SQL 通过游标导航存储过程的结果
由于遗留的报告生成系统,我需要使用游标来遍历存储过程的结果集。系统通过打印结果集中每一行的数据来生成报告输出。重构报告系统远远超出了这个问题的范围。
据我所知,DECLARE CURSOR 语法要求其源是 SELECT 子句。但是,我需要使用的查询存在于生成并执行动态 SQL 的 1000 多行存储过程中。
有谁知道如何将存储过程的结果集放入游标中?
我尝试了显而易见的方法:
Declare Cursor c_Data For my_stored_proc @p1='foo', @p2='bar'
作为最后的手段,我可以修改存储过程以返回它生成的动态 sql,而不是执行它,然后我可以将此返回的 sql 嵌入到另一个字符串中,最后执行它。比如:
Exec my_stored_proc @p1='foo', @p2='bar', @query='' OUTPUT
Set @sql = '
Declare Cursor c_Data For ' + @query + '
Open c_Data
-- etc. - cursor processing loop etc. goes here '
Exec @sql
有什么想法吗?有谁知道通过游标从存储过程遍历结果集的任何其他方法?
谢谢。
Due to a legacy report generation system, I need to use a cursor to traverse the result set from a stored procedure. The system generates report output by PRINTing data from each row in the result set. Refactoring the report system is way beyond scope for this problem.
As far as I can tell, the DECLARE CURSOR syntax requires that its source be a SELECT clause. However, the query I need to use lives in a 1000+ line stored procedure that generates and executes dynamic sql.
Does anyone know of a way to get the result set from a stored procedure into a cursor?
I tried the obvious:
Declare Cursor c_Data For my_stored_proc @p1='foo', @p2='bar'
As a last resort, I can modify the stored procedure to return the dynamic sql it generates instead of executing it and I can then embed this returned sql into another string and, finally, execute that. Something like:
Exec my_stored_proc @p1='foo', @p2='bar', @query='' OUTPUT
Set @sql = '
Declare Cursor c_Data For ' + @query + '
Open c_Data
-- etc. - cursor processing loop etc. goes here '
Exec @sql
Any thoughts? Does anyone know of any other way to traverse the result set from a stored proc via a cursor?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将存储过程中的结果放入临时表中,然后从该表中为光标进行选择。
另一种选择可能是将存储过程转换为表值函数。
You could drop the results from the stored proc into a temp table and select from that for your cursor.
Another option may be to convert your stored procedure into a table valued function.
您使用 INSERT ... EXEC 将过程结果推送到表中(可以是临时 #table 或 @table 变量),您可以在该表上打开光标。链接中的文章讨论了此技术可能出现的问题:它不能嵌套,并且会强制围绕过程进行事务。
You use INSERT ... EXEC to push the result of the procedure into a table (can be a temp #table or a @table variable), the you open the cursor over this table. The article in the link discusses the problems that may occur with this technique: it cannot be nested and it forces a transaction around the procedure.
您可以将 SP 执行到临时表中,然后使用游标迭代临时表
create table #temp (columns)
insert into #temp exec my_stored_proc ....
执行游标工作
drop table #temp
You could execute your SP into a temporary table and then iterate over the temporary table with the cursor
create table #temp (columns)
insert into #temp exec my_stored_proc ....
perform cursor work
drop table #temp