January 14, 2011 at 10:17 pm
I have a table that lists "Holidays":
DECLARE @Holiday TABLE (HolidayId int identity(1,1) primary key, HolidayDate DateTime)
INSERT INTO @Holiday(HolidayDate) VALUES('7/4/2011')
INSERT INTO @Holiday(HolidayDate) VALUES('12/24/2011')
INSERT INTO @Holiday(HolidayDate) VALUES('12/25/2011')
INSERT INTO @Holiday(HolidayDate) VALUES('12/31/2011')
INSERT INTO @Holiday(HolidayDate) VALUES('8/11/2011') --* Yea, my birthday is a holiday in my db :)
I need a query to transform holidays into a range like this:
HolidayId Starts Ends
===========================================================
1 7/4/2011 12:00:00 AM 7/4/2011 11:59:59 PM
2 12/24/2011 12:00:00 AM 12/24/2011 11:59:59 PM
.
.
.
Any easy way to do this?
.
January 14, 2011 at 10:56 pm
OK, maybe this is silly, but here's what I came up with. If I understand correctly, this would encapsulate the entire range of the holiday, right down to the millisecond (almost)
SELECT DATEADD(Ms, 2, CAST(HolidayDate AS DateTime)) AS HolidayStartTime, DATEADD(Ms, -2, CAST(DATEADD(day, 1, HolidayDate) AS DateTime)) AS HolidayEndTime FROM Holiday
Any thoughts?
.
January 14, 2011 at 11:57 pm
How's this?
DECLARE @Holiday TABLE (HolidayId int identity(1,1) primary key, HolidayDate DateTime)
INSERT INTO @Holiday(HolidayDate) VALUES('7/4/2011')
INSERT INTO @Holiday(HolidayDate) VALUES('12/24/2011')
INSERT INTO @Holiday(HolidayDate) VALUES('12/25/2011')
INSERT INTO @Holiday(HolidayDate) VALUES('12/31/2011')
INSERT INTO @Holiday(HolidayDate) VALUES('8/11/2011') --* Yea, my birthday is a holiday in my db :)
SELECT HolidayID,
Starts = HolidayDate,
Ends = DateAdd(ms, -2, DateAdd(day, 1, HolidayDate))
FROM @Holiday;
My thoughts:
It looks like you are on SQL 2008. What happens if this datatype gets changes to one of the new datetime2 datatypes? You know, with precision to the 100 nano-seconds?
This is why most people will do the dates as:
declare @StartDate datetime, @EndDate datetime;
set @StartDate = DateAdd(day, DateDiff(day, 0, @StartDate),0);
set @EndDate = DateAdd(day, 1, @StartDate);
SELECT ...
FROM ...
WHERE DateField >= @StartDate -- starts sometime today
AND DateField < @EndDate; -- less than tomorrow
This will work if the time precision goes out to 1000 decimal places.
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
January 15, 2011 at 1:09 pm
That makes good sense. I guess I'm paranoid about times, and I tend to over analyze. Seems like times always come back to bite me.
Thanks!
.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply