V
V
Victor P.2020-06-17 18:18:33
SQL
Victor P., 2020-06-17 18:18:33

What causes sql script to loop?

[MS SQL Server]
Good afternoon, data gets into one [Contact Message In] table, there is a Processed sign, it is set to 0. I need to loop through all such records, somehow process and set Processed to 1. Here is my code:

declare @nullDate datetime = '1753-01-01'
    , @exchangeCode varchar(20) = null;
    
  select top 1 @exchangeCode=No_ from [dbo].[Contact Message In] where Processed=0;
  
  while(@exchangeCode is not null)
  begin
    Print 'start loop ' + @exchangeCode
    
--код обработки, вырезал для краткости

    --помечаем записи обработанными
    update [Contact Message In] set Processed=1, [Received Message Date Time]=getdate() where [email protected] and Processed=0;
    Print 'updated' --вот тут фактически не происходит обновление
    
    --берём следующую строку
    select top 1 @exchangeCode=No_ from [dbo].[Contact Message In] where Processed=0;
    Print 'next loop for ' + @exchangeCode --выводит ту же самую запись, хотя должен брать следующую
    
  end


Actually, I marked it with comments, for example, one entry comes in, the cycle rises to infinity, and if I manually stop the request, then update [Contact Message In] set Processed=1 will work correctly. It does not work when the cycle is running, this is the output I get if I stop it manually:

start loop CNT105740

(1 row affected)

(1 row affected)
updated
next loop for CNT105740
start loop CNT105740

(0 rows affected)

(0 rows affected)
updated
next loop for CNT105740
start loop CNT105740

(0 rows affected)

(0 rows affected)
updated
next loop for CNT105740
start loop CNT105740
....

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Victor P., 2020-06-17
@Jeer

So, who cares, set WAITFOR DELAY '00:00'; after update

D
d-stream, 2020-06-17
@d-stream

Eeeee

update [Contact Message In]
set Processed=1, [Received Message Date Time]=getdate()
where Processed=0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question