I use auto_increment in MySQL or identity(1,1) in SQLServer only if I know that I will never care about the generated identifier.
select last_insert_id() is an easy way, but dangerous.
The method for processing the corresponding identifiers is to save them in the utility table, for example:
create table correlatives( last_correlative_used int not null, table_identifier varchar(5) not null unique );
You can also create a storage procedure to generate and return the next table X identifier
drop procedure if exists next_correlative; DELIMITER // create procedure next_correlative( in in_table_identifier varchar(5) ) BEGIN declare next_correlative int default 1; select last_correlative_used+1 into next_correlative from correlatives where table_identifier = in_table_identifier; update correlatives set last_correlative_used = next_correlative where table_identifier = in_table_identifier; select next_correlative from dual; END // DELIMITER ;
To use him
call next_correlative('SALES');
This allows you to reserve identifiers before inserting a record. Sometimes you want to display the next identifier in a form before completing the insertion and helps isolate it from other calls.
Here is a test script to mess with:
create database testids; use testids; create table correlatives( last_correlative_used int not null, table_identifier varchar(5) not null unique ); insert into correlatives values(1, 'SALES'); drop procedure if exists next_correlative; DELIMITER // create procedure next_correlative( in in_table_identifier varchar(5) ) BEGIN declare next_correlative int default 1; select last_correlative_used+1 into next_correlative from correlatives where table_identifier = in_table_identifier; update correlatives set last_correlative_used = next_correlative where table_identifier = in_table_identifier; select next_correlative from dual; END // DELIMITER ; call next_correlative('SALES');
Wesos de queso
source share