Click here to Skip to main content
15,912,205 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all

I have two dates from date and to date .for eg: 2/3/2013 to 10/12/2013 .i want to split this into corresponding monthly sections in sqlserver 2008 . i want output as below for given fromdate and to date
fromdate todate
2/3/2013 31/3/2012
1/4/2013 30/4/2013
1/5/2013 31/5/2013
...........................
1/12/2013 10/12/2013

how to do this
Thanks in Advance
Amrutha
Posted
Updated 14-Mar-13 18:17pm
v2
Comments
Davidduraisamy 14-Mar-13 8:35am    
give example
Aarti Meswania 14-Mar-13 8:47am    
can you give example of output records you want?

Hi,

try like below.
SQL
DECLARE @startdt DATETIME, @enddt DATETIME
SELECT @startdt =  '2013-02-03', @enddt =  '2013-12-10'

DECLARE @Sessions TABLE (FromDate DateTime, EndDate DateTime)

WHILE @startdt < @enddt
BEGIN

    if(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startdt)+1,0)) > @enddt )
    INSERT INTO @Sessions VALUES (@startdt, @enddt)
    else
    INSERT INTO @Sessions VALUES (@startdt, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startdt)+1,0)))
    SET @enddt = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startdt)+1,0))
    SET  @startdt = DATEADD(DAY,1,@startdt)
END

SELECT * FROM @Sessions


hope it works.
 
Share this answer
 
v2
Comments
amritha444 15-Mar-13 0:29am    
thanks for the response
But this output is not what im looking for

for a input fromdate and to date i want to split as i mentioned in my question. i have an input from date and to this have a difference of more than one month.
for an input 1/1/2013 and 8/4/2013 i want output as
fromdate to date
1/1/2013 31/1/2013
1/2/2013 28/2/2013
1/3/2013 31/2/2013
1/4/2013 8/4/2013
hi all
finally i used this code
SQL
DECLARE @date1 DATETIME, @date2 DATETIME, @date3 DATETIME, @lastdate DATETIME, @totalMonths INT,@totalDays INT,@counter INT
SET @date1 = '10/22/2011'SET @date2 = '05/25/2012'
SET @totalMonths = DATEDIFF(m, @date1, @date2)
        CREATE TABLE #temp_months
        (start datetime, [end] datetime)
        SET @counter = 0
        SELECT @lastdate= DATEADD( D, -1, DATEADD( mm, DATEDIFF( m, 0, @date1 ) + 1, 0 ) )+1;
        WHILE @counter <@totalMonths
        BEGIN
                SELECT @totalDays=DATEDIFF (d,@date1,@lastdate)
                SELECT @date3=DATEADD(dd,-(DAY(DATEADD(mm,1,@date1))),DATEADD(mm,1,@date1))
                INSERT INTO #temp_months(start,[end]) VALUES (@date1,@date3)
                SET @counter = @counter + 1
                SET @date1=@lastdate
                SET @lastdate = DATEADD(Month, 1, @date1)
         END
       SELECT * FROM #temp_months
drop table #temp_months
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900