Using SQL Server 2000
I want to save the details in month wise
User Entry
ID = 001
Fromdate = 01/01/2012
Todate = 29/03/2012
ID = 002
Fromdate =
You could use a numbers table (have you got one yet?) to generate the months:
SELECT
ID,
Period = RIGHT(CONVERT(varchar(10), MonthStart, 103), 7),
/*
alternatively:
Period = RIGHT('0' + RTRIM(MONTH(MonthStart), 2) + '/' + RTRIM(YEAR(MonthStart)),
*/
FromDate = CASE WHEN RangeStart > MonthStart THEN RangeStart ELSE MonthStart END,
ToDate = CASE WHEN RangeEnd < MonthEnd THEN RangeEnd ELSE MonthEnd END
FROM (
SELECT
ID,
RangeStart,
RangeEnd,
Monthstart,
MonthEnd = DATEADD(DAY, -1, DATEADD(MONTH, 1, Monthstart))
FROM (
SELECT
ID = @ID,
RangeStart = @RangeStart,
RangeEnd = @RangeEnd,
MonthStart = DATEADD(MONTH, DATEDIFF(MONTH, 0, @RangeStart), 0)
FROM numbers
WHERE Number BETWEEN 0 AND DATEDIFF(MONTH, @RnageStart, @RangeEnd)
) m
) m
As a temporary substitute for the numbers table, you could use the master..spt_values system table, or, more exactly, its particular subset where type = 'P'
. So, you can just replace the FROM numbers
above with this subselect:
FROM (
SELECT Number
FROM master..spt_values
WHERE type = 'P'
) numbers