Skip to content
Advertisement

Can’t execute a while clause in SQL Server with Dbeaver

I am trying to execute a loop while in Dbeaver with SQL Server, but the statement keeps loading and does not execute it. I just want to print the word ‘ok!’ 3 times.

I’m not sure if it’s a loop problem, a Dbeaver problem, or another.

Can anyone help please?

My code:

DECLARE @cnt INT = 0;

WHILE @cnt < 3
BEGIN
   PRINT 'ok!';
   
END;

Screenshot from Dbeaver

Advertisement

Answer

@cnt never increments, so this loop will never finish. It will never yield control back to the system to let it even show the first ok string. You need to add this:

DECLARE @cnt INT = 0;

WHILE @cnt < 3
BEGIN
   PRINT 'ok!';
   Set @cnt = @cnt + 1;
END;

Anyway, 99 times out of a 100, if you’re writing a loop in SQL at all you’re doing something very wrong. SQL really wants to operating on whole sets at a time, not individual items in the sets via loops.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement