我在MySQL中有一个触发器,如下所示:
DELIMITER $$
CREATE TRIGGER mytrigger
BEFORE INSERT ON people
FOR EACH ROW
BEGIN
SET NEW.first_name = SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 1), ' ', -1);
SET NEW.last_name = SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 3), ' ', -1);
SET NEW.middle_name = IF(LENGTH( NEW.name) - LENGTH(REPLACE( NEW.name, ' ', ''))>1
,SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 2), ' ', -1)
,NULL);
END$$
DELIMITER ;
我转而使用PostgreSQL,因为Heroku的MySQL ClearDB选项要求计划花费过多的金钱才能使用触发器
我的问题是:我已尝试过所有内容,如何让这个触发器在PostgreSQL中运行?
答案 0 :(得分:0)
用https://github.com/pornel/mysqlcompat更新我的PostgreSQL数据库后。我能够成功并正确地重新格式化我的触发器,看起来像这样:
触发器功能如下:
CREATE OR REPLACE FUNCTION name_split()
RETURNS trigger AS
$BODY$BEGIN
NEW.first_name := SUBSTRING_INDEX(SUBSTRING_INDEX(NEW.name, ' ', 1), ' ', -1);
NEW.last_name := IF(LENGTH( NEW.name) - LENGTH(REPLACE( NEW.name, ' ', ''))>1
,SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 3), ' ', -3)
,SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 3), ' ', -2));
NEW.middle_name := IF(LENGTH( NEW.name) - LENGTH(REPLACE( NEW.name, ' ', ''))>1
,SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 2), ' ', -2)
,NULL);
RETURN NEW;
END;$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
实际触发器显示:
CREATE TRIGGER split
BEFORE INSERT OR UPDATE
ON actors
FOR EACH ROW
EXECUTE PROCEDURE name_split();