【问题标题】:SQL Server: Check constraintSQL Server:检查约束
【发布时间】:2015-05-14 10:53:42
【问题描述】:

我正在尝试在 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')

但是,当我对该特定学生运行插入并添加一门课程时,该学生已经超过其通过的分数限制,检查不会阻止插入。

请帮忙!

【问题讨论】:

  • 您是否需要 pnr 的总分配点 > 45 或课程和作业的任何一个分配点 > 45?
  • 你的函数忽略了它的参数。这可能是首先要解决的问题。
  • 学生已经获得的总分不得超过45分。
  • 将 pnr 值硬编码到该函数中是不是一个错误。
  • 我只是用那个值来测试,也可以是@pnr,但没有区别。

标签: sql-server constraints


【解决方案1】:

不知道你的函数的逻辑,但语法应该是这样的.....

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

【讨论】:

  • 如果 OP 想要总分配点 > 45,您可以使用 having sum(assignmentPoints) > 45 而不是 where assignmentPoints > 45
  • 这不考虑学生已经获得的分数总和。我尝试将您的语法与我使用过的 sum 查询一起使用,但是它不起作用 =(
【解决方案2】:
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 分的课程,它将返回“False”,如果他不学习,它将返回“False”。因此,要么结果小于 45,例如 35。要么它会说 null。无论哪种方式,结果都是“假”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多