我有以下表格:
CREATE TABLE public.fv
(
producer text NOT NULL,
version text NOT NULL,
CONSTRAINT fv_pkey PRIMARY KEY (producer, version)
)
CREATE TABLE public.fv_parameters
(
name text NOT NULL,
CONSTRAINT f_parameters_pkey PRIMARY KEY (name)
)
我想在fv_parameters
插入内容时自动更新fv
。所以我创建了一个触发器:
CREATE TRIGGER insert_to_subtables
AFTER INSERT OR UPDATE
ON public.fv
FOR EACH ROW
EXECUTE PROCEDURE public.insert_to_subtables();
CREATE OR REPLACE FUNCTION public.insert_to_subtables()
RETURNS trigger AS
$BODY$
BEGIN
INSERT INTO parameters values(NEW.producer || '_' || NEW.version,'producer');
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION public.insert_to_subtables()
OWNER TO "PUBLIC";
然而,它一直给我错误:
ERROR: record "new" has no field "producer"
CONTEXT: SQL statement "INSERT INTO parameters values(NEW.producer || '_' || NEW.version,'producer')"
我不明白我做错了什么?显然,我的表fv
有一个名为producer
的字段,我正在向其插入一个新行,因此它必须包含producer
字段?..请帮助
编辑解决了,但仍然不确定如何,我只是删除了所有触发器(我只有2个,但在不同的表中命名相同),并再次声明它们。现在它可以工作
答案 0 :(得分:0)
我修改了函数以返回记录 - 否则它将无法正常工作......下面主要是你的代码 - 没有出错的错误......
t=# CREATE TABLE public.fv
(
producer text NOT NULL,
version text NOT NULL,
CONSTRAINT fv_pkey PRIMARY KEY (producer, version)
)
;
CREATE TABLE public.fv_parameters
(
name text NOT NULL,
CONSTRAINT f_parameters_pkey PRIMARY KEY (name)
);
CREATE TABLE
CREATE TABLE
t=# create table parameters(a text,b text);
CREATE TABLE
t=# CREATE OR REPLACE FUNCTION public.insert_to_subtables()
RETURNS trigger AS
$BODY$
BEGIN
INSERT INTO parameters values(NEW.producer || '_' || NEW.version,'producer');
RETURN NEW; END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE FUNCTION
t=# CREATE TRIGGER insert_to_subtables
AFTER INSERT OR UPDATE
ON public.fv
FOR EACH ROW
EXECUTE PROCEDURE public.insert_to_subtables();
CREATE TRIGGER
t=# insert into fv select 'a','b';
INSERT 0 1
t=# update fv set version='2';
UPDATE 1
t=# select * from fv;
producer | version
----------+---------
a | 2
(1 row)