如何在sql查询中检查所有时隙

4uqofj5v  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(296)

我必须编写查询来根据时隙更新roomid比较房间
我有这个表格数据

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,但我需要检查他预订的appointfrom和appointto是否可用

mzsu5hc0

mzsu5hc01#

你的问题没有说明你是如何得到你的输入或者你想如何处理被禁止的更新(抛出一个错误?)。此解决方案将参数作为输入,不允许更新时不执行任何操作。我还提供了对客户何时有多个预约的支持。
where子句使用(not)exists来只选择可更新的记录。

-- 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)

相关问题