如何在sql查询中检查所有时隙
我必须编写查询以根据时间段更新roomid比较房间 我有这个表格数据如何在sql查询中检查所有时隙,sql,sql-server,sql-server-2008,sql-server-2012,Sql,Sql Server,Sql Server 2008,Sql Server 2012,我必须编写查询以根据时间段更新roomid比较房间 我有这个表格数据 customerid appointmentfrom appointmentto roomid ---------------------------------------------------------------------------- 1 2020-07-18 10:00:00.000 2020-07-18 11:30:0
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,但我需要检查他正在预订的约会From和AppointTo是否可用您的问题没有说明如何获取输入或如何处理禁止的更新抛出错误?。此解决方案将参数作为输入,不允许更新时不执行任何操作。我还包括对客户何时有多个约会的支持 where子句使用仅选择可更新记录
-- 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)
抱歉roomid是另一个值为1,2,2的列。您是否也使用SQL Server 2008或2012?2008是完全不受支持的,因此如果您正在使用它,您现在应该真正查看升级路径。@AJMi,可能会有帮助。这一条不会有帮助,因为我必须比较是否已在客户1试图将其房间号从上午10点更新为上午11点30分的这段时间内预订了约会,如果预订了,我不允许更新