Thursday, March 8, 2012

Create new Date table with a stored proceedure

Hi,

I have a table from which I need to create a report via MSRS2005, however the data in the table is awful in its construction and I was hoping to be able to use a stored proceedure to create a new table in which I can manupulate the data, but my T-SQL programming skills aren't that clever, so if anyone can offer any advice I'd be most grateful:

In the existing table there are two columns; StartDate and EndDate which is pretty self explanitory - what I would like to do is create a new table with only one date column and if there is more than one day between StartDate and EndDate I would like it to fill in every date in between.

For example, if the StartDate is 01/06/2007 and the EndDate 10/06/2007 I'd like the new table to list dates 01/06/2007 through 10/06/2007 inclusive in one column.

Is this possible? All suggestions welcome.

Thanks in advance,

Paul

Might be the below code will help you.

Code Snippet

CREATE PROCEDURE FillDates
@.StartDate DATETIME,
@.EndDate DATETIME
AS
BEGIN
IF datediff(day,@.StartDate,@.EndDate) >0
BEGIN
CREATE TABLE #Calander(CalanderDay DateTime)
WHILE(@.StartDate<=@.EndDate)
BEGIN
INSERT #Calander SELECT @.StartDate
SET @.StartDate = DATEADD(day,1,@.StartDate)
END
SELECT CONVERT(VARCHAR,CalanderDay,103) FROM #Calander
END
ELSE
PRINT 'No'
END
GO

EXEC FillDates '06/01/2007', '06/10/2007'
GO

Thanks,

R@.j

No comments:

Post a Comment