0

I am developing a web application which will allow users to enter a start date and an end date. As I would like this to show up later in a calendar, I believe I need to insert every date between the start date and end date into the database table. For example: 01/01/2012 02/01/2012 03/01/2012 04/01/2012

Is there an easy way of doing this when I have just the start date and end date, e.g. 01/01/2012 and 04/01/2012?

Thanks

2
  • Use a stored procedure which takes the start and end date, or since you're already running asp.net, just call INSERT from a loop. Commented Aug 13, 2012 at 17:06
  • Please use unambiguous date formats (e.g. YYYYMMDD). It's not immediately obvious what country you're in and therefore whether 04/01/2012 is April 1st or January 4th. You can tell by reading a bit more, but why make that hard? Commented Aug 13, 2012 at 17:18

2 Answers 2

1

Rather than a loop, you could try:

;WITH x(n) AS
(
  SELECT TOP (DATEDIFF(DAY, @StartDate, @EndDate) + 1) 
   ROW_NUMBER() OVER (ORDER BY [object_id]) - 1
   FROM sys.all_objects
)
-- INSERT dbo.table_name(date_column)
SELECT DATEADD(DAY, n, DATEADD(DAY, DATEDIFF(DAY, '19000101', @StartDate), '19000101'))
FROM x;

(Comment out the INSERT when you trust the logic and the output.)

Also if 2000+ days is not a large enough swing, you could change to sys.all_columns (7500+) or use your own numbers table.

Sign up to request clarification or add additional context in comments.

Comments

0

I question the need to do this based on your stated requirements, however, this is how:

DECLARE @InsertDate DATETIME = @StartDate;
WHILE @InsertDate <= @EndDate
BEGIN
    INSERT dbo.MyTable (Date) VALUES (@InsertDate)
    SET @InsertDate = @InsertDate + 1 --SQL does implicit conversion from integer to date (1 = 1 day)
END

EDIT: to address comment, this is also valid (possibly recommended, though I've never had an issue with the implicit conversion when used with DATETIME)

    SET @InsertDate = dateadd(d, 1, @InsertDate)

2 Comments

I recommend against the implicit shorthand. This doesn't work with DATE, for example. Just type DATEADD, it's much safer and it doesn't change your billable hours.
You've never had an issue with the implicit conversion because you haven't tried it with DATE, or DATETIME2, or TIME, or DATETIMEOFFSET.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.