我想创建一个触发器和一个执行以下操作的函数:每次在表SalesOrderDetail中插入一个新行时,该函数从表SalesOrderHeader中找到相应的CustomerID,然后它将+1添加到Customer表中相应的number_of_sales
SalesOrderDetail
+---------+-------------------------+
| SalesOrderID | SalesOrderDetailID |
+---------+-------------------------+
| value1 | value4 |
| value1 | value5 |
| value2 | value6 |
| value3 | value7 |
| value3 | value8 |
| value4 | value9 |
+---------+-------------------------+
SalesOrderHeader
+---------+-----------------+
| SalesOrderID | CustomerID |
+---------+-----------------+
| value1 | value10 |
| value2 | value11 |
| value3 | value12 |
| value4 | value13 |
+---------+-----------------+
Customer
+---------+--------------------+
| CustomerID | Number_of_sales |
+---------+--------------------+
| value10 | value14 |
| value11 | value15 |
| value12 | value16 |
| value13 | value17 |
+---------+--------------------+
代码如下:
CREATE OR REPLACE FUNCTION new_order_detail()
RETURNS trigger AS
$BODY$
BEGIN
DROP TABLE IF EXISTS CustomerInfo;
CREATE TEMP TABLE CustomerInfo AS
SELECT* FROM(SELECT CustomerID FROM(
SELECT * from SalesOrderHeader
WHERE SalesOrderHeader.SalesOrderID = (SELECT SalesOrderID FROM SalesOrderDetail ORDER BY SalesOrderID DESC limit 1))AS Last_Entry) AS Common_Element;
IF CustomerInfo.CustomerID = Customer.CustomerID THEN
UPDATE Customer
SET number_of_items = number_of_items + 1;
END IF;
END;
$BODY$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS new_order ON SalesOrderDetail;
CREATE TRIGGER new_order
AFTER INSERT OR UPDATE ON SalesOrderDetail
FOR EACH ROW EXECUTE PROCEDURE new_order_detail();
当我在SalesOrderDetail表中插入内容时,出现以下错误:
PL / pgSQL函数new_order_detail()在SQL语句第3行错误: 表" customerinfo"缺少FROM子句条目第1行:选择 CustomerInfo.CustomerID = Customer.CustomerID ^ QUERY:SELECT CustomerInfo.CustomerID = Customer.CustomerID CONTEXT:PL / pgSQL function new_order_detail() IF的第12行 **********错误**********
错误:缺少FROM-clause条目表" customerinfo" SQL状态: 42P01上下文:PL / pgSQL函数new_order_detail()IF中的第12行
我做错了什么?对不起,英语不是我的母语。
答案 0 :(得分:0)
首先,您需要注意区分大小写的pgsql。如果您没有明确使用“”,则会将所有内容转换为小写。
接下来,您的程序应该是这样的:
select CustomerID from SalesOrderHeader where SalesOrderDetail.SalesOrderID = SalesOrderHeader.SalesOrderID into custID;
UPDATE Customer SET number_of_items = number_of_items + 1 where CustomerID = custID ;