SQL Server:无限 WHILE EXISTS 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7632372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Server: Endless WHILE EXISTS loop
提问by Nemanja Vujacic
I have problem with the following WHILE EXISTS loop. Could you consider what can be reason why it is endless loop and why it doesn't update values?
我对以下 WHILE EXISTS 循环有疑问。你能考虑一下它无限循环的原因以及它为什么不更新值的原因吗?
declare @part varchar(20)
while exists ((select top 1 * from part1 p where isnull(brojRacuna,'')=''))
begin
set @part=''
set @part=(select top 1 partija from part1 p where isnull(brojRacuna,'')='')
begin tran
update part1
set BrojRacuna= (select dbo.dev_brojracuna (@part))
where partija like @part
print @part
commit
end
EDIT 1:Because I didn't find solution in first moment, I created cursor and updated data in that way. After that I found that left couple rows that are not updated, because function had an issue with data and couldn't update values for that rows. In that case, fields have been empty always and loop became endless.
编辑 1:因为我第一时间没有找到解决方案,所以我以这种方式创建了游标并更新了数据。之后我发现剩下的几行没有更新,因为函数有数据问题并且无法更新该行的值。在那种情况下,字段一直是空的,循环变得无穷无尽。
采纳答案by Dippi
I don't understand why you select the partija value, since you have it in the where clause, you can simplify a lot this way:
我不明白你为什么选择 partija 值,因为你在 where 子句中有它,你可以通过这种方式简化很多:
declare @part varchar(20)
while exists ((select 1 from part1 p where isnull(brojRacuna,'')='' and partija='1111'))
begin
begin tran
update part1
set BrojRacuna= (select dbo.dev_brojracuna ('1111'))
where partija like '1111'
commit
end
By the way, if you have an endless loop, maybe the function dev_brojracuna doesn't return the correct value, and brojRacuna remains unaltered.
顺便说一句,如果你有一个无限循环,也许函数 dev_brojracuna 没有返回正确的值,而 brojRacuna 保持不变。