I have a table in which the primary key is in 'BCB001'
format, I would like to know if there is any way to format AUTO_INCREMENT
so that I can fill in the field I need.
I have a table in which the primary key is in 'BCB001'
format, I would like to know if there is any way to format AUTO_INCREMENT
so that I can fill in the field I need.
The incremental auto field was created precisely so as not to be touched by the user, making it possible to generate changes and erase data from the DB without generating collateral damage. In addition to facilitating the referential integrity of the same.
If all this still does not convince you the AUTO-INCREMENT
is for int, not for varchar attributes, so you could not do what you're wanting.
I hope I helped you. Greetings
One solution would be to create a INT AUTO_INCREMENT
field in your table apart from the code to save the desired format.
CREATE TABLE 'test' (
'id' int(11) unsigned zerofill NOT NULL AUTO_INCREMENT,
'cod' varchar(6) DEFAULT NULL,
'nombre' varchar(100) DEFAULT NULL,
PRIMARY KEY ('id')
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Then create a Trigger to update the field cod
before (before) , making use of the function Concat to concatenate the fixed format (BCB)
with what it returns LPad (number, amount, chararrellenar) filling in with 0
on the left to what you return the LAST_INSERT_ID +1 (ultimoidinsertado) , not exceeding Length
in this example is 3 (secondparameter)
DELIMITER $$
CREATE TRIGGER tg_insert_test
BEFORE INSERT ON test
FOR EACH ROW
BEGIN
if (SELECT COUNT(*) FROM prueba)=0 THEN
SET NEW.cod= 'BCB001';
else
SET NEW.cod= CONCAT('BCB', LPAD(LAST_INSERT_ID()+1, 3, '0'));
END IF;
END$$
DELIMITER ;
To insert just make the classic INSERT
.
INSERT INTO test (nombre) values ('Nombre1');