我想创建一个考试安排系统。现在我的目标是避免用户在SQL Server 2008中为同一个房间插入冲突时间表。 例如:
房间 202 有
的时间表02/27/2017 4:00pm - 5:00pm
那么如果房间 202 的用户输入是
,该怎么办?02/27/2017 3:50pm - 5:10pm
显然这是冲突。
如果我要在两者之间使用,显然它不适用于给定的示例输入。
请帮助。 感谢
答案 0 :(得分:0)
就像尼克所说,between
正是你所需要的。在这种情况下,与exists
或not exists
结合使用,您将能够避免计划冲突。
只有当同一个房间的同一天没有条目进入时,才会执行insert
,其开始或结束时间介于新时段之间(表示存在冲突)。
看看这个例子:
MS SQL Server 2008架构设置:
CREATE TABLE schedule
([room] int, [date] date, [start] time, [finish] time)
;
INSERT INTO schedule
([room], [date], [start], [finish])
SELECT 202, '2017-02-26', '16:00', '17:00'
WHERE NOT EXISTS (SELECT *
FROM schedule
WHERE room = '202' AND date = '2017-02-26' AND
(start BETWEEN '16:00' AND '17:00'
OR finish BETWEEN '16:00' AND '17:00'))
;
INSERT INTO schedule
([room], [date], [start], [finish])
SELECT 202, '2017-02-26', '15:50', '17:10'
WHERE NOT EXISTS (SELECT *
FROM schedule
WHERE room = '202' AND date = '2017-02-26' AND
(start BETWEEN '15:50' AND '17:10'
OR finish BETWEEN '15:50' AND '17:10'))
;
INSERT INTO schedule
([room], [date], [start], [finish])
SELECT 202, '2017-02-26', '15:00', '15:59'
WHERE NOT EXISTS (SELECT *
FROM schedule
WHERE room = '202' AND date = '2017-02-26' AND
(start BETWEEN '15:00' AND '15:59'
OR finish BETWEEN '15:00' AND '15:59'))
;
查询1 :
SELECT *
FROM schedule
<强> Results 强>:
| room | date | start | finish |
|------|------------|------------------|------------------|
| 202 | 2017-02-26 | 16:00:00.0000000 | 17:00:00.0000000 |
| 202 | 2017-02-26 | 15:00:00.0000000 | 15:59:00.0000000 |
在应用程序中,使其看起来像这样:
伪:
SELECT count(*)
FROM schedule
WHERE room = '202' AND date = '2017-02-26' AND
(start BETWEEN '15:00' AND '15:59'
OR finish BETWEEN '15:00' AND '15:59')
if count(*) = 0 then
INSERT INTO schedule
([room], [date], [start], [finish])
SELECT 202, '2017-02-26', '15:00', '15:59'
else
ERROR "CONFLICT WITH ANOTHER SCHEDULE"
end if