在两个日期和两次列SQL Server之间的可用房间预订

时间:2018-12-05 12:05:46

标签: sql sql-server tsql

我的桌子上有四列。

STARTDATE               STARTTIME   ENDDATE                 ENDTIME       ROOMCODE
2018-10-16 00:00:00.000 14:00       2018-10-16 00:00:00.000 18:00         CS0001
2018-10-16 00:00:00.000 18:00       2018-10-16 00:00:00.000 22:00         CS0001

我要检查预订是否可用

       select CONFERENCE_ROOM from COR_CONFERENCE_BOOKING  where 
(cast(STARTDATE as datetime) + cast(START_TIME as time) >= cast('2018-10-16' 
as datetime) + cast(DATEADD(MINUTE, 01, '14:00') as time) 
and cast(STARTDATE as datetime) + cast(START_TIME as time) < cast('2018-10- 
  16' as datetime) + cast('18:00' as time)) 
  or (cast(ENDDATE as datetime) + cast(END_TIME as time) >= cast('2018-10-16' 
   as datetime) + cast(DATEADD(MINUTE, 01, '14:00') as time) 
   and cast(ENDDATE as datetime) + cast(END_TIME as time) < cast('2018-10-16' 
  as datetime) + cast('18:00' as time)) 
    and CONFERENCE_ROOM='CS0001'

如果要在通过日期和时间的选择查询中找到任何数据,那么我要选择数据,然后预订房间,否则免费。

请解决此查询。对我来说太复杂了。

1 个答案:

答案 0 :(得分:1)

这是MS SQL Server的示例代码。
我假设这是您的目标RDBMS,因为示例SQL使用该DATEADD函数。

它只会返回表变量中的第一条记录。

因为第二条记录不在范围内。

declare @Table table (
 ID INT PRIMARY KEY IDENTITY(1,1), 
 STARTDATE date, 
 STARTTIME time, 
 ENDDATE date, 
 ENDTIME time, 
 CONFERENCE_ROOM varchar(6)
);

insert into @Table (STARTDATE, STARTTIME, ENDDATE, ENDTIME, CONFERENCE_ROOM) values
('2018-10-16','14:00:00','2018-10-16','18:00:00','CS0001'),
('2018-10-16','18:00:00','2018-10-16','22:00:00','CS0001');

select ID, CONFERENCE_ROOM 
from @Table t
where (CAST(STARTDATE AS DATETIME) + CAST(STARTTIME as DATETIME)) < (CAST(ENDDATE AS DATETIME) + CAST(ENDTIME as DATETIME))
  and (CAST(STARTDATE AS DATETIME) + CAST(STARTTIME as DATETIME)) >= CAST('2018-10-16 14:00' AS DATETIME)
  and (CAST(ENDDATE AS DATETIME) + CAST(ENDTIME as DATETIME))     <= CAST('2018-10-16 18:00' AS DATETIME)
  and CONFERENCE_ROOM = 'CS0001';

如果STARTTIME和ENDTIME是VARCHAR而不是TIME数据类型?
然后,为避免尝试转换废话数据时出错,可以改用TRY_CAST。
(如果您的MS SQL Server版本提供TRY_CAST) 因为当转换失败时,TRY_CAST会返回NULL而不是错误。

示例:

select ID, CONFERENCE_ROOM 
from @Table t
where STARTDATE = ENDDATE
  and TRY_CAST(STARTTIME AS TIME) < TRY_CAST(ENDTIME AS TIME)
  and STARTDATE = CAST('2018-10-16' AS DATE)
  and TRY_CAST(STARTTIME AS TIME) >= CAST('14:00' AS TIME)
  and TRY_CAST(ENDTIME AS TIME)   <= CAST('18:00' AS TIME)
  and CONFERENCE_ROOM = 'CS0001';