1

我正在编写 SP 以插入 FinalExams 表。我的意思是,如果第一次考试从 9:30 开始并在 10:30 结束,则同一班级的两次考试不应冲突;在此期间不应进行任何考试,因此如果我尝试在 10:15 插入考试,则不应执行插入语句

这是我的代码

ALTER PROC [dbo].[InsertFinalExams] --1,1,3,'12/10/2013','11:00','11:30',1
(
@pClassID int,
@pSectionID int,
@pCourseID int,
@pExamDate datetime,
@pStartHoure datetime,
@pFinishHoure datetime,
@pCreatedBy int
)
AS 
--check if the exam period is valid 
--means if the exam start at hour it cant be finish at any time before the same hour
IF  DATEPART(hh,@pStartHoure) >=   DATEPART(HH,@pFinishHoure ) AND DATEPART(MI,@pStartHoure) >=   DATEPART(MI,@pFinishHoure ) 
    BEGIN
        PRINT('Please enter valid period')
        RETURN
    END
--To check if there is a class has a section and a course
IF NOT EXISTS (SELECT 'TRUE'
           FROM SectionsClasses 
           WHERE ClassID=@pClassID 
           AND SectionID=@pSectionID)
  OR
    NOT EXISTS (SELECT 'TRUE'
            FROM Courses
            WHERE CourseID=@pCourseID )

    BEGIN
        PRINT ('Please choose valid class and section and Course')
        RETURN
    END
--check if there is no exam at the same time
IF EXISTS (SELECT 'TRUE' 
            FROM FinalExams 
            WHERE ClassID=@pClassID
                  AND SectionID=@pSectionID 
                  AND ExamDate=@pExamDate
                  OR @pStartHoure between DATEADD(minute,-1, StartHoure) AND DATEADD(minute,-1,  FinishHoure)   
                  OR  @pFinishHoure between DATEADD(minute,-1, StartHoure) AND  DATEADD(minute,-1, FinishHoure)
                --  OR StartHoure > @pStartHoure
                  --AND FinishHoure < @pFinishHoure
                  )
    BEGIN 
        PRINT('Please choose another time for this exam')
        RETURN
    END
ELSE
        INSERT INTO FinalExams
        Values
            (
            @pClassID,
            @pSectionID,
            @pCourseID,
            @pExamDate,
            @pStartHoure,
            @pFinishHoure,
            @pCreatedBy,
            getdate(),
            null,
            null
            )

我认为我在 WHERE 子句中有问题

4

1 回答 1

0

您想检查日期范围是否重叠,看看这个很好的答案:确定两个日期范围是否重叠

尝试以下操作:

--check if there is no exam at the same time
IF EXISTS (SELECT 'TRUE' 
            FROM FinalExams 
            WHERE ClassID=@pClassID
                  AND SectionID=@pSectionID 
                  AND ExamDate=@pExamDate
                  AND @pStartHoure <= FinishHoure 
                  AND @pFinishHoure >= StartHoure)   
于 2013-10-22T08:01:55.777 回答