Tuesday, September 18, 2012

In this simple example I want to demonstrate how you can use while loop, temporary table and declare & use variables in sql server itself.  


  • First of all declare two variables of type datetime & set values of these variable as shown below:


    declare @dtfrm datetime,@dtto datetime;
    set @dtfrm='2012-01-15';
    set @dtto='2012-02-10';


  • Now declare a temporary table as :


    declare @temp table(DateColumn date);


  • Now I started a while loop from start date and continue to run it until start date is equal to end date : 

    while(@dtfrm<=@dtto)
    begin
       insert @temp
       select @dtfrm;
       set @dtfrm=DATEADD(day,1,@dtfrm);
    end

  • Finally select all dates from temporary table as :

    select * from @temp

0 comments:

Post a Comment