You must Sign In to post a response.
  • Category: SQL Server

    How to use For loop in sql function?


    Are you looking for information on For loop usage in SQL? Want to know how to use For loop in sql function? Read this thread to learn more about For loop with examples.



    How to use for loop in sql function which return int value?
  • #727998
    Hi,

    I don't think, there is a FOR loop in TSQL.

    You can use WHILE loop in a stored procedure/function.

    WHILE (condition)
    BEGIN

    // Your Logic

    BREAK;
    END

    Check the below link for how to use while loop with break & continue

    http://blog.sqlauthority.com/2008/02/04/sql-server-simple-example-of-while-loop-with-break-and-continue/

    Thanks & Regards,
    Mahesh Durgam

  • #728002
    Hi,

    Use below synatx for looping in SQL statements

    WHILE (CONDITIONS)
    BEGIN
    --STATEMENTS
    END

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #728005
    There is no For loop present Either you can make use of a Cursor or else use a While loop as below.


    While(Condition)
    Begin
    -- Select * from AnilInfo
    End

    Thanks & Regards
    Anil Kumar Pandey
    Microsoft MVP, DNS MVM

  • #728013
    Use Cursors

  • #728055
    You need to try below statement to use For loop in SQL function.Syntax of for loop in SQL.
    FOR loop_counter IN [REVERSE] lowest_number.....highest_number
    LOOP
    {
    .statements.
    }
    END LOOP;

    code behind
    DECLARE
    a number(1);
    b number(1);
    BEGIN

    FOR a IN 1..10 LOOP

    FOR b IN 1..10 LOOP
    dbms_output.put_line('a is: '|| a || ' and b is: ' || b);

    END loop innerloop;

    END loop outerloop;

    END;

  • #728152
    Hi,

    You can try with below code snippet:

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
    PRINT @intFlag
    SET @intFlag = @intFlag + 1
    END
    GO


    Best regards
    Bashar


  • This thread is locked for new responses. Please post your comments and questions as a separate thread.
    If required, refer to the URL of this page in your new post.