如何在PostgreSQL的MySql中更改触发器?

时间:2015-02-19 15:18:50

标签: mysql postgresql

我试图将此触发器代码从MySQL更改为PostgreSQL语法。

在MySQL中看起来像这样:

delimiter $$
create trigger trggBeforeInsertTUser before insert on TUsuario FOR EACH ROW
begin
set @LastCod=(select max(codUsr) from TUsuario);
if @LastCod is null then
   set @LastCod="USRX0000000";
end if;
set @partText=mid(@LastCod, 1, 8);
set @partNum=mid(@LastCod, 9, 7)+1;
set @longNumber=(select length(@partNum));
set @codNum=concat(repeat('0', 7-@longNumber), @partNum);
set @codNum=concat(@partText, @codNum);
set NEW.codUsr=(select @codNum);
end

在Postgres中我尝试了这个:

CREATE TRIGGER trggBeforeInsertTUser BEFORE INSERT on TUser 
  EXECUTE PROCEDURE sp_incremental();

CREATE OR REPLACE FUNCTION sp_incremental () RETURNS TRIGGER AS trggBeforeInsertTUser
BEGIN
set LastCod=(select max(codUser) from TUser);
if LastCod is null then
    set LastCod="USRX0000000";
end if;
set partText=mid(LastCod, 1, 8);
set partNum=mid(LastCod, 9, 7)+1;
set longNumber=(select length(partNum));
set codNum=concat(repeat('0', 7-longNumber), partNum);
set cod=concat(partText, codNum);
set NEW.codUsr=(select cod);
END

但没有成功。任何帮助?

1 个答案:

答案 0 :(得分:2)

嗯,你在PostgreSQL的语法方面遇到了一些问题。我建议你阅读:http://www.postgresql.org/docs/9.3/static/plpgsql-trigger.html

您可以尝试这样的事情,只需编译,测试并查看是否可以:

CREATE OR REPLACE FUNCTION sp_incremental() RETURNS TRIGGER AS $sp_incremental$
DECLARE 
    LastCod character varying(100);
    partText character varying(100);
    partNum character varying(100);
    longNumber bigint;
    codNum character varying(100);
    cod character varying(100);
BEGIN
    LastCod := (select max(codUser) from TUser);
    if LastCod is null then
        LastCod := "USRX0000000";
    end if;
    partText := mid(LastCod, 1, 8);
    partNum := mid(LastCod, 9, 7) + 1;
    longNumber := (select length(partNum));
    codNum := concat(repeat('0', 7 - longNumber), partNum);
    cod := concat(partText, codNum);
    NEW.codUsr := (select cod);
END;
$sp_incremental$ LANGUAGE plpgsql;

CREATE TRIGGER trggBeforeInsertTUser BEFORE INSERT on TUser 
  EXECUTE PROCEDURE sp_incremental();

另外,根据需要设置数据类型。