I need help with creating a trigger that will generate a protocol number. The following sequence must be followed:
323926YYYYMMDDXXXXXX
- 323926 = fixed number
- YYYY = year
- MM = month
- DD = day
- XXXXXX = Number we must automatically generate from 1 that will go to 999999
My difficulty is that this incremental number should return to 000001 after the course of the day, summarizing: Every day the first protocol generated must start with the number 000001
My Code :
CREATE OR REPLACE FUNCTION crm.novo_ticket()
RETURNS trigger AS
$BODY$
BEGIN
NEW.protocolo = '323926' || TO_CHAR(NEW.data_cadastro,'YYYYMMDD') || '000001';
RETURN NEW;
END $BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
Sorted out
SELECT
lpad(CAST((SELECT COUNT(1) + 1 INTO quant
FROM
crm.ticket a
WHERE
a.data_cadastro::DATE = CURRENT_TIMESTAMP(0)::DATE;)as VARCHAR),6,'0');
CURRENT_TIMESTAMP(0)::DATEcan be simplified toCURRENT_DATEAlso: the;after the cast is wrongcount(*) + 1to generate that number is a broken approach if you have more then one concurrent user in your system (plus: it's not going to scale for many rows at all). Using a sequence is the only scalable and concurrency safe way to generate unique numbers. Evan's answer will be a lot more efficient as well