PostgreSQL 11.1
I am using the following trigger to obtain a "new" chart number from the chart_gap table:
CREATE FUNCTION phoenix.next_chart()
RETURNS trigger
LANGUAGE 'plpgsql'
COST 100
VOLATILE NOT LEAKPROOF
AS $BODY$
BEGIN
-- Check for empty chart number
IF NEW.chart_number is null or NEW.chart_number = 0 THEN
WITH ins AS (
SELECT chart_number
FROM chart_gap
WHERE pg_try_advisory_xact_lock(chart_number)
LIMIT 1
)
DELETE FROM chart_gap c
USING ins i
WHERE i.chart_number = c.chart_number
RETURNING i.chart_number INTO NEW.chart_number;
END IF;
RETURN NEW;
END;
$BODY$;
How would I add a test to be sure the chart_number that is returned does not already exist (in table patients) and if it does, then force a loop to get the next chart number in the table, etc.., until an unused chart_number is found? That is, the trigger must return new and unused chart_numbers.
TIA
Note: my initial thoughts are to use recursive cte, but think a straight forward loop might be faster?