我需要一些帮助来修复Postgres 9.4表格触发器配置。在过去的几天里,我一直在尝试几种不同的stackoverflow搜索方法而没有成功。如何修复我的代码以满足下面描述的简单要求?
要求是根据当前总线状态字段值更改颜色字段状态。颜色更新应仅针对单行而不是整个BusColor表。因此,当AI_Bus'1145'运行状态(BusStatus)为INSERT或UPDATED时,触发器会将颜色字段更改为正确的关联颜色。假设'1145'的BusStatus从'NSCH'更新为'SCH',那么触发器会将颜色值从'white'更改为'yellow'。下面是我的Posgresql 9.4对象配置:
CREATE TABLE BusColor (
AI_Bus serial PRIMARY KEY,
BusStatus character varying NOT NULL,
color character varying NOT NULL );
SELECT * FROM “MyDB”.”BusColor”;
AI_Bus BusStatus color
1145 NSCH white
1146 SCH yellow
1147 NSCH white
1148 OPER green
CREATE TRIGGER “UpdateBusColor” BEFORE INSERT OR UPDATE ON “BusColor”
FOR EACH STATEMENT EXECUTE PROCEDURE “TrigFuncBusColor”();
CREATE FUNCTION “TrigFuncBusColor”() RETURNS trigger
LANGUAGE plpgsql
AS $$BEGIN
IF (TG_OP = ‘UPDATE’) THEN
IF (NEW.”BusStatus” <> OLD.”BusStatus”) THEN
IF NEW.“BusStatus” = ‘NSCH’ THEN
UPDATE “MyDB”.”BusColor” SET “color” = ‘white’;
RETURN NEW;
END IF;
IF NEW.“BusStatus” = ‘SCH’ THEN
UPDATE “MyDB”.”BusColor” SET “color” = ‘yellow’;
RETURN NEW;
END IF;
IF NEW.“ID_BusStatus” = ‘OPER’ THEN
UPDATE “MyDB”.”BusColor” SET “color” = ‘green’;
RETURN NEW;
END IF;
END IF;
END IF;
RETURN NULL;
END;
$$;
答案 0 :(得分:2)
为什么要为每个总线状态使用条件,只需选择已更换状态的颜色并更新所有状态为新状态的颜色。
CREATE FUNCTION “TrigFuncBusColor”() RETURNS trigger
LANGUAGE plpgsql
declare newColor varchar;
AS $$BEGIN
IF (TG_OP = ‘UPDATE’) THEN
IF (NEW.”BusStatus” <> OLD.”BusStatus”) THEN
SELECT "color" INTO newColor FROM “MyDB”.”BusColor” WHERE BusStatus = NEW.“BusStatus” LIMIT 1;
UPDATE “MyDB”.”BusColor” SET “color” = newColor where BusStatus = NEW.“BusStatus”;
RETURN NEW;
END IF;
END IF;
RETURN NULL;
END;