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

lfapxunr  于 2023-08-02  发布在  SQL Server
关注(0)|答案(1)|浏览(123)

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

rsaldnfx

rsaldnfx1#

@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 operate on whole sets at a time, not individual items in the sets via loops.

相关问题