How to do for loop in SQL SERVER?

1
BEGIN
 <<LOOP_EXTERNO>>
 FOR V_EXTERNO IN 1..20 LOOP
  DBMS_OUTPUT.PUT_LINE('Contador externo: ' || V_EXTERNO);
  <<LOOP_INTERNO>>
   FOR V_INTERNO IN 1..5 LOOP
    DBMS_OUTPUT.PUT_LINE('Contador interno: ' || V_INTERNO);
    IF V_EXTERNO = 10 THEN
     EXIT LOOP_EXTERNO;
    END IF;
  END LOOP INTERNO;
 END LOOP EXTERNO;
END;
/

This command is in PL/SQL , and I do not understand how to do it in SQL server , I do not know if it's the same thing or something changes.

Could anyone help me?

    
asked by anonymous 26.10.2016 / 15:00

2 answers

0

The sql server does not have FOR LOOP , instead it uses WHILE . , for this you have to create variables as counter.

Your code looks like this.

declare @V_EXTERNO int = 1
declare @V_INTERNO int = 1

BEGIN
    WHILE @V_EXTERNO < 21   
    BEGIN
        print 'Contador externo: ' + cast(@V_EXTERNO as varchar(10));
        WHILE @V_INTERNO < 6        
        BEGIN
             print 'Contador interno: ' + cast(@V_INTERNO as varchar(10));
             SET @V_INTERNO = @V_INTERNO + 1;
        END;
       SET @V_EXTERNO = @V_EXTERNO + 1;
       SET @V_INTERNO = 1;
    END;
END;
    
26.10.2016 / 15:12
1

In SQL SERVER there is no FOR LOOP , you should simulate it using WHILE LOOP .

Basic syntax;

DECLARE @cnt INT = 0;

WHILE @cnt < cnt_total
BEGIN
   {...statements...}
   SET @cnt = @cnt + 1;
END;

cnt_total ; The number of times you want WHILE LOOP to rotate.
statements ; The declarations of the code that will be executed with each passing of WHILE LOOP.

See this example below;

DECLARE @cnt INT = 0;

WHILE @cnt < 10
BEGIN
   PRINT 'StackOverflow';
   SET @cnt = @cnt + 1;
END;

PRINT 'Feito';
GO
    
26.10.2016 / 15:14