I need some help in fixing my Postgres 9.4 Table Trigger configuration. For the past couple of days I have been trying several different stackoverflow search ideas without success. How can I fix my code to meet the simple requirements described below?
The requirement is to change the color field status based upon the current bus status field value. The color update should only occur for the single row and NOT the entire BusColor table. So when AI_Bus ‘1145’ operational status (BusStatus) is INSERT OR UPDATED, the trigger would change the color field to the proper associated color. Say that the BusStatus for ‘1145’ is updated from ‘NSCH’ to ‘SCH’, then the trigger would change the color value from ‘white’ to ‘yellow’. Below are my Posgresql 9.4 object configurations:
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;
$$;
update set ....command you just set the value for the new field likeNEW.color = 'somevalue'FOR EACH STATEMENTtoFOR EACH ROWand use theNEW.fieldFOR EACH ROWand changed the updates fields back to the original.CREATE TRIGGER “UpdateBusColor4” BEFORE INSERT OR UPDATE OF “BusStatus”, color ON “BusColor” FOR EACH ROW EXECUTE PROCEDURE “TrigFuncBusColor”();CREATE FUNCTION “TrigFuncBusColor”() RETURNS trigger LANGUAGE plpgsql AS $$BEGIN IF TG_OP = ‘UPDATE’ THEN IF (OLD.”BusStatus” <> NEW .”BusStatus”) THEN IF (NEW.“BusStatus” = ‘SCH’) THEN NEW.“color” = ‘yellow’; RETURN NEW; END IF; IF (NEW.“BusStatus” = ‘NSCH’) THEN NEW.“color” = ‘white’; RETURN NEW; END IF; IF (NEW.“BusStatus” = ‘OPER’) THEN NEW.“color” = ‘green’; RETURN NEW; END IF; END IF; END IF; RETURN NULL; END; $$;