SQL Server:检查约束

问题描述:

我想在SQL Server中创建一个检查约束。SQL Server:检查约束

我有一张名为Studies的表,它有'pnr','courseCode','assignment'。
我有一个名为Student的表,它有'pnr'。
我有一张名为Course的表,它有'courseCode'。
我有一个名为Assignment的表,它有'courseCode','assignment','assignmentPoints'。

现在我想检查一下,防止管理员将pnr插入Studies如果该pnr目前已经参加值得多点的课程,则限制为45分。

我已经得到这么多,但它不起作用。

create function EnrollmentFunction (@pnr varchar(10)) returns varchar(10) 
as 
begin 
    if exists (
      select sum(assignmentPoints) as Points 
      from Assignment a 
       join Studies s 
       on a.courseCode = s.courseCode 
        and a.assignmentName = s.assignmentName 
        and a.sectionName = s.sectionName 
        and pnr = @pnr 
      where assignmentPoints > 45) 
     return 'False' 
    return 'True' 
end 

alter table Studies 
with check add constraint CK_Points 
check (dbo.EnrollmentFunction(pnr) = 'True') 

然而,当我运行对特定学生插入和添加课程时学生已超过它通过对点的极限,检查没有阻止插件。

请帮忙!

+0

您是否需要pnr的总分配点数大于45或任何一个课程分配点和任务大于45? – ughai

+0

你的函数忽略了它的参数。这可能是第一个要解决的问题。 –

+0

学生已经参加的积分不得超过45分。 –

不知道你的功能,但语法应该是这个样子的逻辑.....

create function EnrollmentFunction 
(@pnr varchar(10)) 
returns varchar(10) 
as 
begin 
    DECLARE @RtnValue varchar(10); 

    if exists (select 1 
       from Assignment a 
       join Studies s on a.courseCode = s.courseCode 
           and a.assignmentName = s.assignmentName 
           and a.sectionName = s.sectionName 
           and pnr = @pnr 
       where assignmentPoints > 45 
       ) 
     BEGIN 
      SET @RtnValue = 'False' 
     END 
    ELSE 
     BEGIN 
     SET @RtnValue = 'True' 
     END 

    RETURN @RtnValue;  
end 
+0

如果OP要求总分配点数大于45,那么可以使用'sum(assignmentPoints)> 45'来代替'where assignmentpointss> 45' – ughai

+0

这不考虑学生已经采取的积分总和。我试着使用你的语法与我使用的总和查询,但它没有工作,但=( –

create function EnrollmentFunction 
(@pnr varchar(10)) 
returns varchar(10) 
as 
begin 
    DECLARE @RtnValue varchar(10); 

    if exists (select sum(assignmentPoints) as Points from Assignment a join Studies s 
on a.courseCode = s.courseCode and a.assignmentName = s.assignmentName and a.sectionName = s.sectionName and pnr = @pnr 
where assignmentPoints > 45 
       ) 
     BEGIN 
      SET @RtnValue = 'True' 
     END 
    ELSE 
     BEGIN 
     SET @RtnValue = 'False' 
     END 

    RETURN @RtnValue;  
end 

这不起作用。它会返回“假”如果学生正在课程价值45分,如果不符合则返回'假'。所以要么结果是小于45,比如说35。或者它会说空。无论哪种方式,结果都是'假'。