Reputation: 6590
I have table i.e. BookingDetails. BookingDetails containt following fields.
CustomerID
DateFrom
DateTo
TimeFrom
TimeTo
BookingDetails contains n records.
CustomerID DateFrom DateTo TimeFrom TimeTo
11137 2012-08-14 2012-08-16 00:33:46 03:33:46
11138 2012-08-15 2012-08-17 08:00:00 00:31:03
11139 2012-08-16 2012-08-17 22:46:25 00:46:25
I want to select records between given information DateFrom, DateTo, TimeFrom, TimeTo.
I have do following query
declare @fDate date
set @fDate = '2012-08-14'
declare @tDate date
set @tDate = '2012-08-16'
declare @fTime time
set @fTime ='12:33:46 AM'
declare @tTime time
set @tTime='12:31:03 AM'
SELECT BookingDetails.CustomerID
FROM BookingDetails
WHERE (DateFrom between @fDate and @tDate) And (BookingDetails.DateFrom >= @fDate and BookingDetails.DateTo<=@tDate)
and(TimeFrom between CONVERT(varchar(15),cast(@fTime as time) , 108) and CONVERT(varchar(15),cast(@tTime as time) , 108))
and (TimeFrom >=CONVERT(varchar(15),cast(@fTime as time) , 108) and TimeTo <=CONVERT(varchar(15),cast(@tTime as time) , 108))
Time save in database is in 24 hours format. Time used in query is 12Hours format thats why i convert it to 24 hours format in query.
Is this query is correct or I have to change it?
This Query doesn't return any value. I want to select records between @fDate , @tDate, @fTime, @tTime
I expect Result for first two customerID i.e. 11137,11138
Upvotes: 1
Views: 284
Reputation: 280262
Why not pass the start and end as DATETIME instead of as separate values? In fact, why are you storing DATE and TIME separately when it's clear these are points in time and the two values are more important together than apart? Anyway given the current schema you need to stop converting to string. Try this:
DECLARE @b TABLE (
CustomerID INT,
DateFrom DATE,
DateTo DATE,
TimeFrom TIME,
TimeTo TIME
);
INSERT @b VALUES (11137,'2012-08-14','2012-08-16','00:33:46','03:33:46'),
(11138,'2012-08-15','2012-08-17','08:00:00','00:31:03'),
(11139,'2012-08-16','2012-08-17','22:46:25','00:46:25');
declare @fDate date
set @fDate = '2012-08-14'
declare @tDate date
set @tDate = '2012-08-16'
declare @fTime time
set @fTime ='12:33:46 AM'
declare @tTime time
set @tTime='12:31:03 AM'
;WITH x AS
(
SELECT
CustomerID, DateFrom, TimeFrom, DateTo, TimeTo,
[Start] = DATEADD(SECOND, DATEDIFF(SECOND,'00:00',TimeFrom),
CONVERT(DATETIME, DateFrom)),
[End] = DATEADD(SECOND, DATEDIFF(SECOND,'00:00',TimeTo),
CONVERT(DATETIME, DateTo))
FROM @b
)
SELECT * FROM x WHERE [Start]
BETWEEN CONVERT(DATETIME, @fDate) + CONVERT(DATETIME, @fTime)
AND CONVERT(DATETIME, @tDate) + CONVERT(DATETIME, @tTime);
Upvotes: 1