如何检查 sql 查询中所有时间段的时间

How to check time all time slots in sql query

我必须编写查询来更新 roomid 根据时间段比较房间

我有这个table数据

customerid    appointmentfrom            appointmentto               roomid
----------------------------------------------------------------------------   
    1         2020-07-18 10:00:00.000    2020-07-18 11:30:00.000        1
    2         2020-07-18 10:30:00.000    2020-07-18 11:15:00.000        2
    3         2020-07-18 11:15:00.000    2020-07-18 11:59:00.000        2

我不应该允许 customerid 1 将他的 roomid 更新为 2,因为 roomid 2 已经被预订了那个时段

customerid 1 正在尝试将 roomid 更新为 2,但我需要检查他正在预订的 appointmentfrom 和 appointmentto 是否可用

您的问题没有说明您如何获得输入或您希望如何处理被禁止的更新(抛出错误?)。该解决方案将参数作为输入,并且在不允许更新时不执行任何操作。我还包括对客户何时有多个约会的支持。

where 子句使用 (not) exists 仅 select 可更新记录。

-- create example
declare @data table
(
    customerid int,
    appointmentfrom datetime,
    appointmentto datetime,
    roomid int
);

insert into @data (customerid, appointmentfrom, appointmentto, roomid) values
(1, '2020-07-18 10:00:00.000', '2020-07-18 11:30:00.000', 1),
(2, '2020-07-18 10:30:00.000', '2020-07-18 11:15:00.000', 2),
(3, '2020-07-18 11:15:00.000', '2020-07-18 11:59:00.000', 2);


-- solution (with parameters)
declare @customerid int = 1;                                    -- specify customer
declare @appointmentfrom datetime = '2020-07-18 10:00:00.000';  -- specify customer appointment
declare @newroomid int = 2;                                     -- specify target room

update d
set d.roomid = @newroomid
from @data d
where d.customerid = @customerid            -- select customer...
  and d.appointmentfrom = @appointmentfrom  -- ... and his appointment
  -- look for any unwanted overlapping meetings on the target room
  and not exists (  select top 1 'x'
                    from @data d2
                    where d2.roomid = @newroomid
                      and d2.appointmentto > d.appointmentfrom
                      and d2.appointmentfrom < d.appointmentto );
-- (0 rows affected)