I assume that your barcode here is basically INT(7) UNSIGNED ZEROFILL with the prefix VARCHAR .
To save this as a SQL-only solution, I simply created a MySQL function. The trick is to treat the numeric part of the barcode as an unsigned, zero-filled integer - this keeps your leading zeros in tact.
CREATE FUNCTION `barcode_increment`(`sin_barcode` VARCHAR(12), `sin_prefix` VARCHAR(5)) RETURNS varchar(12) READS SQL DATA DETERMINISTIC COMMENT 'increments a barcode that has a prefix' BEGIN DECLARE i_barcode_num INT(7) UNSIGNED ZEROFILL; SET i_barcode_num = CAST(REPLACE(sin_barcode, sin_prefix, '') AS UNSIGNED); SET i_barcode_num = i_barcode_num + 1; RETURN CONCAT(sin_prefix, i_barcode_num); END
You can call this function through a standard SQL query, for example:
SELECT barcode_increment('PU0000012', 'PU') AS new_barcode
What will give you PU0000013
Note. If the PU is always a prefix, you can simply declare and set it in the function itself - removing the need to pass it as a parameter.
Alternatively, you can do this in one (slightly dirty) query that relies on LPAD and not ZEROFILL :
SELECT CONCAT('PU', LPAD(CAST(REPLACE('PU0001234', 'PU', '') AS UNSIGNED) + 1, 7, 0))
This example will give you PU0001235
source share