我想创建一个触发函数,以向一列提供一个值,该值是由两个其他具有预定值的列串联而生成的。如果该值已经存在,我将在连接的值后相应地增加第三列。
EX:
column1 -> 'aaa'
column2 -> 'bbb'
concatenated value -> 'aaabbb'
column1 -> 'xxx'
column2 -> 'yyy'
concatenated value -> 'xxxyyy'`
如果已经存在行,其值为'aaabbb',则第三列将递增为:
1 | aaabbb
2 | aaabbb
3 | aaabbb
1 | xxxyyy
2 | xxxyyy
答案 0 :(得分:0)
您可以尝试使用此代码,其工作只能插入。但是您也可以复制触发器并更改以进行更新。
create table test ( column1 varchar, column2 varchar, column3 varchar);
CREATE TRIGGER t_before_test
BEFORE insert
ON test
FOR EACH ROW
EXECUTE PROCEDURE fnt_test();
CREATE OR REPLACE FUNCTION fnt_test()
RETURNS trigger LANGUAGE plpgsql AS
$BODY$
declare
v_count int := 0;
BEGIN
select 1 into v_count from test where column1 = NEW.column1 and column2 = NEW.column2;
if ( NEW.column1 is not null and NEW.column2 is not null and v_count > 0) then
NEW.column3 := NEW.column1 || NEW.column2;
end if;
RETURN NEW;
END;
$BODY$;
insert into test ( column1, column2 ) values ( '1', '2');
select * from test;
答案 1 :(得分:0)
不确定是否要保存串联值。这个不会保存它,但是您当然可以将连接的值保存到new.concatenated_column
中:
create function f_test ()
returns trigger
language plpgsql
as $$
begin
new.column3 := (
select coalesce(max(t.column3) + 1, 1)
from test as t
where t.column1 || t.column2 = new.column1 || new.column2
);
return new;
end;
$$
create trigger tr_test
before insert
on test
for each row execute procedure f_test();