触发器中的 Postgres 未定义列

Postgres undefined column in trigger

我在 Orderlist 中为此触发器插入一行时收到错误消息:

ERROR:  column "qty_in_stock" does not exist
LINE 1: SELECT qty_in_stock > 0
           ^
QUERY:  SELECT qty_in_stock > 0
CONTEXT:  PL/pgSQL function books_upd() line 6 at CASE
****** Error **********

ERROR: column "qty_in_stock" does not exist
SQL state: 42703
Context: PL/pgSQL function books_upd() line 6 at CASE

这是我的代码:

INSERT INTO orderlist VALUES (12,1235,6)

CREATE OR REPLACE FUNCTION books_upd()
RETURNS trigger as $bookupd$
BEGIN
UPDATE books
SET qty_in_stock=qty_in_stock - NEW.quantity
WHERE isbn=NEW.isbn;
CASE WHEN qty_in_stock > 0 THEN
UPDATE stockmanager
set quantity=quantity+NEW.quantity
WHERE isbn=NEW.isbn;
END CASE;   

RETURN NEW;
END;
$bookupd$ LANGUAGE plpgsql;

许多关于在 qty_in_stock 周围加上引号的论坛建议 - 同样的错误。

Table 信息:

Table 书籍:“"isbn"”-pk “"title"” “"author"” “"qty_in_stock"” “"price"” “"cost"” “"year-published"” “"publisherid"”

Table 库存经理: “"isbn"”-pk,fk “"quantity"”

感谢任何帮助。

您不能像那样使用 CASE 语句,也不能在 SQL 语句之外引用 table 的列。您需要做的是将新值存储在一个变量中,然后将其与 if 语句一起使用:

CREATE OR REPLACE FUNCTION books_upd()
  RETURNS trigger as 
$bookupd$
DECLARE 
  l_qty integer;
BEGIN
  UPDATE books
    SET qty_in_stock = qty_in_stock - NEW.quantity
  WHERE isbn=NEW.isbn
  RETURNING qty_in_stock INTO l_qty;

  if l_qty > 0 THEN
    UPDATE stockmanager
       set quantity= quantity + NEW.quantity
    WHERE isbn = NEW.isbn;
  END IF;   

  RETURN NEW;
END;
$bookupd$ 
LANGUAGE plpgsql;