I am trying to auto increment a varchar column from a table. It is prefix with "PU". I use this to grab the last number and increment it by one.
I tried this query below:
SELECT
CONCAT(
LEFT( BARCODE, 2 )
,
MAX(
RIGHT( BARCODE, LENGTH(BARCODE)-2 )
* 1 )
+1
)
as newbarcode FROM KGU WHERE HW_TYPE='STANDARD PURGE UNIT';
The last barcode is PU0000012. It returns a PU13. It removes the 0.
So I tried replacing it with:
LEFT( BARCODE, 7 )
It returned PU0000013 which is correct. But suppose I put a PU1234567 as last entry. It returns: PU000001234568.
Any suggestions? I am using php btw. If an option is to use php I am open to it. But I prefer it to be solve in sql query if possible.
Split your id in two parts. Prefix = String = "AEC" and Index = Integer = "0001". Then you can Index++ and concanate Prefix + Index to get your ID.
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .
To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.
The auto increment in SQL is a feature that is applied to a field so that it can automatically generate and provide a unique value to every record that you enter into an SQL table. This field is often used as the PRIMARY KEY column, where you need to provide a unique value for every record you add.
Try this:
<?php
// fetch the very last entry
$Barcode = 'PU000001234567';
preg_match("/(\D+)(\d+)/", $Barcode, $Matches); // Matches the PU and number
$ProductCode = $Matches[1];
$NewID = intval($Matches[2]);
$NewID++;
$BarcodeLength = 12;
$CurrentLength = strlen($NewID);
$MissingZeros = $BarcodeLength - $CurrentLength;
for ($i=0; $i<$MissingZeros; $i++) $NewID = "0" . $NewID;
$Result = $ProductCode . $NewID;
echo $Result;
// insert into database with $Result
Returns: PU000001234568
try below query-
SELECT CONCAT(LEFT(BARCODE, 2),LPAD(@n := @n + 1,7,0)) AS newbarcode
FROM KGU AS a
JOIN (SELECT @n := 13) AS m
WHERE HW_TYPE='STANDARD PURGE UNIT';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With