Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment a varchar in sql query

Tags:

php

mysql

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.

like image 976
aozora Avatar asked Aug 07 '15 09:08

aozora


People also ask

How can I increment varchar value in SQL Server?

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.

How do you auto increment a character in SQL?

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) .

How can insert auto increment value in SQL query?

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.

What is auto increment value in SQL?

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.


2 Answers

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

like image 90
zanderwar Avatar answered Sep 22 '22 14:09

zanderwar


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';
like image 27
Zafar Malik Avatar answered Sep 25 '22 14:09

Zafar Malik