检查插入值对另一个表的

时间:2017-11-13 19:41:22

标签: sql sql-server

我在我的数据库中添加了一个表:

***Enrollments***
CourseID
Student ID
EnrollmentDateTime

我已经有一张桌子了:

***Courses***    
CourseID    
StartDate

当有人将数据插入注册表时,我想检查注册日期是否小于开始日期之前/之前;我知道需要做什么,但我缺乏如何做的语法。到目前为止,我有以下内容,但我对如何继续进行了处理。

Create Table Enrollments(
    StudentID int NOT NULL Foreign Key REFERENCES dbo.Students(StudentID),
    CourseID int NOT NULL Foreign Key REFERENCES dbo.Courses(CourseID),
    EnrollmentDateTime Datetime NOT NULL CHECK (dbo.fCheckDate(EnrollmentDateTime, CourseID) = 1))

...

create function dbo.fCheckDate (@StartDate Datetime, @CourseID int)
Returns bit
AS 
Begin 
 Return(SELECT E.StartDate 
    FROM dbo.Enrollments E
    WHERE @CourseID = E.CourseID
End
go

1 个答案:

答案 0 :(得分:0)

这种基于功能的检查非常昂贵。但是,您需要一个函数来返回课程日期:

create function dbo.getStartDate (@CourseID int)
Returns datetime
AS 
Begin 
     Return (SELECT c.StartDate 
             FROM dbo.Courses c 
             WHERE c.CourseID = @CourseID 
            );
End;

Create Table Enrollments (
    StudentID int NOT NULL Foreign Key REFERENCES dbo.Students(StudentID),
    CourseID int NOT NULL Foreign Key REFERENCES dbo.Courses(CourseID),
    EnrollmentDateTime Datetime NOT NULL CHECK (EnrollmentDateTime < getStartDate(CourseID))
);