我正在尝试创建一个触发器和函数,用于将已插入表customers中的值插入到表purchase中。
表customers的列
1-customer_id序列主键在采购中引用customer_id
2-c_名称VARCHAR
3-数量双精度
表购买的列
1-customer_id序列主键2金额双精度
触发器和函数的代码:
CREATE OR REPLACE FUNCTION auto_insert_purchases()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$body$
BEGIN
insert into purchases(customer_id,purchase) values
(NEW.customer_id,NEW.purchase);
END
$body$
CREATE TRIGGER tr_auto_insert_purchases
AFTER INSERT ON customers
EXECUTE PROCEDURE auto_insert_purchases()
正如您所看到的,它应该获取新行数据并将其插入到表中,但在这样做并插入到customers
之后:
insert into customers values(2,'Stewie Griffin',4.99);
我收到此错误消息:
ERROR: null value in column "customer_id" of relation "purchases" violates not-null
constraint
DETAIL: Failing row contains (null, null).
CONTEXT: SQL statement "insert into purchases(customer_id,purchase) values
(NEW.customer_id,NEW.purchase)"
auto_insert_purchases() PL/pgSQL fonksiyonu, 3. satır, SQL ifadesi içinde
SQL state: 23502
为什么失败的行包含空值?我使用的NEW关键字不正确吗?
1条答案
按热度按时间niwlg2el1#
您可能只是忘记在
CREATE TRIGGER tr_auto_insert_purchases AFTER INSERT ON customers
之后编写for each row
语句