PostgreSQL 11.1
ERROR: null value in column "chart_number" violates not-null constraint
O.K., I'm clearly doing something wrong here, but I don't see it.
Table patients has
COLUMN chart_number integer NOT NULL;
The Error is coming from the trigger:
CREATE OR REPLACE FUNCTION phoenix.next_chart()
RETURNS trigger
LANGUAGE 'plpgsql'
COST 100
VOLATILE NOT LEAKPROOF
AS $BODY$
BEGIN
IF NEW.chart_number is null or NEW.chart_number = 0 THEN
LOOP
EXIT WHEN 0 = (select count(*) from patients where chart_number = NEW.chart_number);
SELECT nextval('chartsequence') INTO NEW.chart_number;
END LOOP;
END IF;
RETURN NEW;
END;
$BODY$;
The sequence "chartsequence" is defined in the usual way:
CREATE SEQUENCE chartsequence START 1;
What I am trying to do is have the loop exit when the sequence value does NOT exist in table patients.
Any help is most appreciated. TIA