如何在存储过程中迭代记录集?
我需要从存储过程迭代记录集,并使用每个字段作为参数执行另一个存储过程。我无法在代码中完成此迭代。我在互联网上找到了示例,但它们似乎都涉及计数器。我不确定我的问题是否涉及计数器。我需要相当于 foreach 的 T-SQL
目前,我的第一个存储过程将其记录集存储在临时表 #mytemp 中。我假设我会像这样调用辅助存储过程:
while (something)
execute nameofstoredprocedure arg1, arg2, arg3
end
I need to iterate over a recordset from a stored procedure and execute another stored procedure using each fields as arguments. I can't complete this iteration in the code. I have found samples on the internets, but they all seem to deal with a counter. I'm not sure if my problem involved a counter. I need the T-SQL equivalent of a foreach
Currently, my first stored procedure stores its recordset in a temp table, #mytemp. I assume I will call the secondary stored procedure like this:
while (something)
execute nameofstoredprocedure arg1, arg2, arg3
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要创建一个游标来循环遍历记录集。
示例表:
光标:
这里是有关如何创建它们的 MSDN 链接。
http://msdn.microsoft.com/en-us/library/ms180169。 aspx
这就是为什么我使用 Raise Error 而不是 PRINT 进行输出。
https: //kemiller2002.github.io/2014/11/24/Wait-Wait-Don-t-Tell-Me-On-Second-Thought.html
You need to create a cursor to loop through the record set.
Example Table:
Cursor:
Here is a link to MSDN on how to create them.
http://msdn.microsoft.com/en-us/library/ms180169.aspx
This is why I used Raise Error instead of PRINT for output.
https://kemiller2002.github.io/2014/11/24/Wait-Wait-Don-t-Tell-Me-On-Second-Thought.html
在 SQL 过程中循环遍历行非常容易。您只需要使用光标即可。下面是一个示例:
让我们考虑一个表 Employee,其中包含列 NAME 和 AGE,其中包含 50 条记录,并且您必须执行一个存储过程说 TESTPROC 它将获取每行的名称和年龄参数。
确保释放游标以避免错误。
It's very easy to loop through the rows in SQL procedure. You just need to use a cursor. Here is an example:
Let us consider a table Employee with column NAME and AGE with 50 records into it and you have to execute a stored procedure say TESTPROC which will take name and age parameters of each row.
Make sure you deallocate the cursor to avoid errors.
试试这个(光标自由循环):
工作示例:
输出:
try this (cursor free looping):
working example:
OUTPUT: