0

在 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 周围加上引号 - 同样的错误。

表信息:

表书:““isbn”“-pk”“title”““author”““qty_in_stock”“”price“”“cost”“year-published”“publisherid”

表 stockmanager: ""isbn""-pk,fk ""quantity""

任何帮助表示赞赏。

4

1 回答 1

1

您不能使用这样的 CASE 语句,也不能在 SQL 语句之外引用表的列。您需要做的是将新值存储在变量中,然后将其与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;
于 2015-12-02T15:55:45.107 回答