>我需要 MSSQL Server 中的一个函数,该函数作为参数将得到@startTime @endTime,并将检查表预订(也有开始时间和结束时间),如果询问日期范围适合表中的时间范围和返回 1 如果是,如果不是,则返回 0。有点混乱,我会在桌子上更好地解释(至少我希望如此)
我有表:
|:-----------------------|----------------------:|
| startDate | endDate |
|:-----------------------|----------------------:|
| 2017-01-25 00:00:00.000|2017-01-25 12:00:00.000|
| 2017-01-25 13:00:00.000|2017-01-25 14:00:00.000|
|:-----------------------|----------------------:|
需要检查是否可以预订,即:
@startTime = 2017-01-25 13:30:00.000
@endTime = 2017-01-25 15:00:00.000
并且应该返回 0,因为这段时间有保留。
我已经尝试通过@startTime>开始日期和@endTime <结束日期来执行此操作,但条件是检查每一行,我需要检查整个表。>
亲切问候
你可以做这样的事情:
select (case when exists (select 1
from reservations r
where r.startDate <= @endTime and
r.endDate >= @startTime
)
then 0 else 1
end) as available;
逻辑很简单。 如果第一个时间段在第二个时间段结束之前开始,第一个时间段在第二个时间段开始后结束,则两个时间段重叠。
create table info(startdate datetime, enddate datetime);
insert into info values
('2017-01-01', '2017-01-05'),
('2017-01-03', '2017-01-06'),
('2017-01-01', '2017-01-15'),
('2017-01-02', '2017-01-13'),
('2017-01-12', '2017-01-18');
declare @StartDate datetime = '2017-01-03';
declare @EndDate datetime = '2017-01-04'
select *
from info
where startdate <= @StartDate and enddate >= @EndDate;
+----+---------------------+---------------------+
| | startdate | enddate |
+----+---------------------+---------------------+
| 1 | 01.01.2017 00:00:00 | 05.01.2017 00:00:00 |
+----+---------------------+---------------------+
| 2 | 03.01.2017 00:00:00 | 06.01.2017 00:00:00 |
+----+---------------------+---------------------+
| 3 | 01.01.2017 00:00:00 | 15.01.2017 00:00:00 |
+----+---------------------+---------------------+
| 4 | 02.01.2017 00:00:00 | 13.01.2017 00:00:00 |
+----+---------------------+---------------------+