我有桌子,即 BookingDetails 。 BookingDetails包含以下字段。
客户id
DateFrom
DateTo
TimeFrom
TimeTo
BookingDetails 包含n条记录。
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
我想在给定信息 DateFrom , DateTo , TimeFrom , TimeTo 之间选择记录。
我做了以下查询
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))
数据库中的时间保存为24小时格式。查询中使用的时间是12小时格式,这就是我在查询中将其转换为24小时格式的原因。
此查询是正确的还是我必须更改它?
此查询不返回任何值。我想在 @fDate , @tDate , @fTime , @tTime
之间选择记录我期待前两个customerID的结果,即11137,11138
答案 0 :(得分:1)
为什么不将开始和结束作为DATETIME而不是作为单独的值传递?实际上,为什么在明确这些是时间点的时候分别存储DATE和TIME,这两个值比分开更重要?无论如何,根据当前架构,您需要停止转换为字符串。试试这个:
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);