sql:创建调用函数的约束时出错

时间:2018-12-07 18:32:46

标签: sql

我正在尝试制定一个限制条件,以限制学生如果没有订阅该图书馆的借阅书。

LibraryBooks:该表包含您可以在图书馆中找到的书。

idLibrary  |  idBook
1          |  1
1          |  2
1          |  3 
2          |  1

StudentLibrary:表,其中每个学生都订阅了某个图书馆。

idStudent  |  idLibrary
1          |  1
2          |  1

贷款书:显示哪些书是借来的,是谁借来的,从何处借来的。

idStudent  |  idBook     |  idLibrary  
1          |  1          |  1
1          |  2          |  1
1          |  3          |  1
2          |  1          |  2

例如,idStudent = 1的学生无法从idLibrary = 2的图书馆借书。

这是我的代码:

CREATE FUNCTION dbo.CheckFunction(@x int, @y int)
returns int
as begin
    declare @ret int;
    if (select StudentLibrary.idLibrary from StudentLibrary 
                      where @x = StudentLibrary.idStudent and @y = StudentLibrary.idLibrary) != null
        SET @ret = @y;
    else
        SET @ret = 0;  

    return @ret;
end
go

ALTER TABLE LoanBook
ADD CONSTRAINT constraint_student_library
CHECK (LoanBook.idLibrary = dbo.CheckFunction(LoanBook.idStudent, LoanBook.idLibrary))

我遇到以下错误:

  

ALTER TABLE语句与CHECK约束“ constrangere_student_biblioteca”冲突。在数据库“ DataBaseLibraries”的表“ dbo.LoanBook”中发生了冲突。

1 个答案:

答案 0 :(得分:2)

检查以下内容:-

CREATE FUNCTION dbo.CheckStudentCanLoan (@idStudent int, @idLibrary int)
RETURNS int
AS 
BEGIN
  DECLARE @retval int
       -- find if idStuded is registered with this idLibrary
    SELECT @retval = count(*) FROM StudentLibrary
        WHERE idStudent=@idStudent and idLibrary=@idLibrary
  RETURN @retval
END;

ALTER TABLE LoanBook 
  ADD CONSTRAINT CheckStudentCanLoanCon 
  CHECK (dbo.CheckStudentCanLoan(idStudent, idStudent) >0); 

如果用户重复输入,则支票可以等于1,但大于零将起作用。

我使用以下内容进行测试

create table LibraryBooks (idLibrary   int,idBook int)
insert into LibraryBooks values (1,1),(1,2),(1,3),(2,1)
create table StudentLibrary (idStudent     int,idLibrary int)
insert into StudentLibrary values (1,1),(2,1)
create table LoanBook (idStudent int,idBook int,idLibrary  int)

这有效

insert into LoanBook values (1,1,1),(1,2,1),(1,3,1)

这遇到了约束

insert into LoanBook values (1,1,1),(1,2,1),(1,3,1),(2,1,2),(1,1,2)

有预期的错误 消息547,级别16,状态0,第8行 INSERT语句与CHECK约束“ CheckStudentCanLoanCon”冲突。在数据库“ ... \ DATABASE1.MDF”,表“ dbo.LoanBook”的列“ idStudent”中发生了冲突。 该声明已终止。

如果我们想调整您的工作,这可以是一种解决方案:-

CREATE FUNCTION dbo.CheckFunction(@x int, @y int)
returns int
as begin
declare @ret int;
if exists(select StudentLibrary.idLibrary from StudentLibrary 
                  where @x = StudentLibrary.idStudent and @y = StudentLibrary.idLibrary) 
    SET @ret = @y;
else
    SET @ret = 0;  

return @ret;

结束

go

ALTER TABLE LoanBook
ADD CONSTRAINT constraint_student_library
CHECK (LoanBook.idLibrary = dbo.CheckFunction(LoanBook.idStudent, LoanBook.idLibrary))