Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server SQL中的游标替换_Sql Server_Loops_Cursor - Fatal编程技术网

Sql server SQL中的游标替换

Sql server SQL中的游标替换,sql-server,loops,cursor,Sql Server,Loops,Cursor,我是jr级开发人员,正在使用SQL编写一个脚本,尝试迭代select语句中的结果集,对于返回的每一行,获取少量列并将它们传递到存储过程中。我从StackOverflow上找到的其他示例中整理了这个脚本,它已经运行了33分钟。我做了一些研究,现在我发现游标只能作为最后的手段使用( 有人能帮我把它重构成更友好的性能吗?我正在处理的结果集中有419行 declare @docid uniqueidentifier declare @publish_xml nvarchar(max) = null de

我是jr级开发人员,正在使用SQL编写一个脚本,尝试迭代select语句中的结果集,对于返回的每一行,获取少量列并将它们传递到存储过程中。我从StackOverflow上找到的其他示例中整理了这个脚本,它已经运行了33分钟。我做了一些研究,现在我发现游标只能作为最后的手段使用(

有人能帮我把它重构成更友好的性能吗?我正在处理的结果集中有419行

declare @docid uniqueidentifier
declare @publish_xml nvarchar(max) = null
declare @pub_text1 nvarchar(max) = null
declare @pub_text2 nvarchar(max) = 'Physical Mail'
declare @pub_text3 nvarchar(max) = null

declare cur CURSOR LOCAL for
        select d.document_id, d.published_xml, d.published_text1, d.published_text2, d.published_text3 
            from tblCMS_Document d 
            where d.template_id = '357760AD-1D33-4162-A813-20F56901C18D'
open cur

fetch next from cur into @docid, @publish_xml, @pub_text1, @pub_text2, @pub_text3

while @@FETCH_STATUS = 0 BEGIN

    exec [usp_CMS_Document_Publish] @docid, @publish_xml, @pub_text1, 'Physical Mail', @pub_text3

END

CLOSE cur   
DEALLOCATE cur

这并不能回答您的问题,但这可能是光标永远运行的原因。您缺少while循环中的下一个获取:

open cur

fetch next from cur into @docid, @publish_xml, @pub_text1, @pub_text2, @pub_text3

while @@FETCH_STATUS = 0 BEGIN

    exec [usp_CMS_Document_Publish] @docid, @publish_xml, @pub_text1, 'Physical Mail', @pub_text3

    fetch next from cur into @docid, @publish_xml, @pub_text1, @pub_text2, @pub_text3

END

我会将光标查询移动到usp\U CMS\U Document\U Publish中,并以基于集合的方式执行此发布操作。是否无法编辑usp\U CMS\U Document\U Publish?

对于419行,时间的主要用户是exec语句-将其更改为非光标很可能不会加快执行时间。不使用光标是一个很好的选择但是习惯。