PROBLEM USING LOOP IN SQLSERVER

Somesh

Total Post:21

Points:147
Posted by  Somesh
 1505  View(s)
Ratings:
Rate this:
Hi

How to use loop in sqlserver?

Thanks in advance
  1. Amit Singh

    Post:103

    Points:721
    Re: Problem using loop in sqlserver

    Hi somesh,

    This is the sample code for using loop in sqlserver

    Declare @maxNo int
    Declare @i int
    set @maxNo=4
    set @i=1
    print 'Output'
    ---Use while loop----
    while(@i<=@maxNo)
    begin               
        print @i
        set @i=@i+1
    end   

    ----Output-------
    1
    2
    3
    4

  1. Shankar M

    Post:25

    Points:175
    Re: Problem using loop in sqlserver

    Hi Somesh,


    There is no for loop statement in SQL Server. We use only while statements for Looping. Lets have
    a look at this example.

    DECLARE @I INT -- Declaring a Local Variable
    SET @I =0      -- Assigning a Default Value to Local Variable
    WHILE @I <=5   -- Start of the Loop, Evaluates until @I turns to be less than or equal to  5
     BEGIN
        PRINT 'I value is :' + CAST(@I AS VARCHAR(10)) -- Displaying the Present @I value
        SET @I = @I + 1 -- Incrementing the @I value
    END            -- End of Loop 

    Thanks,
    Shankar

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!