You’ll have to do three things:
- Create a table to store the number of the last contract.
- Create a trigger to ensure that each insert uses the sequential number
- Create a function that calculates the next contract number based on the defined rules and the number found in the above table.
No doubt you won’t be able to use the AUTO INCREMENT
mysql.
Something like that:
CREATE TABLE sequencia_contrato (
sequencial INT NOT NULL PRIMARY KEY,
ano INT
);
Trigger:
CREATE TRIGGER numero_contrato BEFORE INSERT ON contrato
FOR each ROW
BEGIN
SET NEW.contrato = PegaNumeroContrato();
END
Function:
Basically you will have to value the table above, add up 10, if I understood that this is what you want. And catch the current year. If the current year is greater than the year recorded in the control table of the sequence, the year there should be updated to the current year and the sequence should be reset. Maybe this isn’t exactly what you want.
CREATE FUNCTION PegaNumeroContrato() RETURNS VARCHAR(10)
BEGIN
//precisa melhorar ainda, falta tratar o ano, por exemplo
DECLARE ultimo_valor INT;
SET ultimo_valor = (SELECT sequencial FROM sequencia_contrato);
SET ultimo_valor = ultimo_valor + 1;
UPDATE sequencia_contrato SET sequencial = ultimo_valor;
SET @resultado = (SELECT concat(lpad(ultimo_valor, 5, '0'), '-', CAST((SELECT ano FROM sequencia_contrato) AS CHAR(4))));
RETURN @resultado;
END
I put in the Github for future reference.
This is a terrible practice, you are in a relational database, you can simply create a field to store this date and use it as a criterion in the querys
– Isvaldo Fernandes
But to follow the relational model I already have the ID field, which follows the standard database, in case I wanted a facility to consult the contracts, so I would no longer have another database, which currently is Microsoft Excel and would leave everything online.
– The Guilherme Henrique
you can build a Trigger on the Insert, give a look Trigger
– Isvaldo Fernandes