SQL Server: Endless WHILE EXISTS loop

63,192

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:

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.

Share:
63,192
Nemanja Vujacic
Author by

Nemanja Vujacic

http://www.maki-apartments.com

Updated on October 25, 2020

Comments

  • Nemanja Vujacic
    Nemanja Vujacic over 3 years

    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?

    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.

  • Nemanja Vujacic
    Nemanja Vujacic over 12 years
    As I said in Comment at my question: I accidentally left one part of code: 'and partija='1111' ' We don't need it here, because I want to update all rows where BrojRacuna is NULL.
  • Dippi
    Dippi over 12 years
    Ok, when I post there wasn't that comment :) Anyway, have you checked the brojRacuna function?
  • Nemanja Vujacic
    Nemanja Vujacic over 12 years
    Of course, I announced comment just in case that you haven't seen it. ;-) You can take a look at EDIT1, there is written about function. Thanks for answer and suggestions!