1

我有桌子,即BookingDetails。BookingDetails 包含以下字段。

客户ID

日期从

日期至

时间从

时间到

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

我想在给定信息DateFromDateToTimeFromTimeTo之间选择记录。

我有以下查询

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

4

1 回答 1

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);
于 2012-08-31T18:34:32.407 回答