PostgreSQL中的触发器功能出错

时间:2015-03-19 18:18:26

标签: database postgresql triggers plpgsql

我的数据库中有三个表 - StudentsBooksBooks2student

  • Students表格有StudentID, First_Name, Last_Name

  • Books表格有ISBN_no, name, no. of copies available

  • Books2Students表格中有StudentID, books issued, issue date, due date

我想创建一个触发器,当学生从books2students删除时,no. of copies表中的Books应该增加,如果我在books2student中插入一本书,那么书中no of copies应该减少。

我写了一个函数和触发器,但是我在函数中遇到错误

CREATE FUNCTION student_to_book()   RETURNS trigger AS  '
BEGIN
  IF tg_op = ''DELETE'' THEN
        UPDATE books 
        SET books.no_of_copies_available = no_of_copies_available+1
        WHERE Books2Students.Book_Issued=books.ISBN_no;

  END IF;
  IF tg_op = ''INSERT'' THEN
        UPDATE books  
        SET books.no_of_copies_available = no_of_copies_available-1
        WHERE Books2Students.Book_Issued=books.ISBN_no;   

  END IF;
END
' LANGUAGE plpgsql;                                                     

我收到错误错误:

ERROR: missing FROM-clause entry for table "books2students"
  Where: PL/pgSQL function student_to_book() line 10 at SQL statement

2 个答案:

答案 0 :(得分:0)

您收到错误是因为您指的是WHERE子句中的books books2students,但没有FROM子句。我假设触发器是针对此表的,因此您可以在更新部件中使用关键字NEW,在删除部件中使用关键字OLD而不是表名。像这样:

IF tg_op = ''INSERT'' THEN
UPDATE books
  SET books.no_of_copies_available = no_of_copies_available-1
  WHERE NEW.Book_Issued=books.ISBN_no;

答案 1 :(得分:0)

有很多问题。这可能有效:

CREATE OR REPLACE FUNCTION student_to_book()
  RETURNS trigger AS
$func$
BEGIN
   IF TG_OP = 'DELETE' THEN
      UPDATE books 
      SET    no_of_copies_available = no_of_copies_available + 1
      WHERE  ISBN_no = OLD.Book_Issued;

   ELSIF TG_OP = 'INSERT' THEN
      UPDATE books  
      SET    no_of_copies_available = no_of_copies_available - 1
      WHERE  ISBN_no = NEW.Book_Issued;
   END IF;
END
$func$ LANGUAGE plpgsql;

Start by reading the manual about the special records OLD and NEW here.

Then read the manual about UPDATE here.

你还没有覆盖TG_OP = UPDATE

通常,MATERIALIZED VIEW是一种更好的方法来跟踪每本书的计数。