How to Auto Increment ID Numbers with Letters and Numbers - mysql

How to Auto Increment ID Numbers with Letters and Numbers, example "KP-0001" it will increment to "KP-0002"
Thank you!

here is a useful article
auto increment with a string of numbers and letters
But basically I encourage you to create your own algorithm on this. You can add that algorithm in BEFORE INSERT trigger. Or you can do that on the front-end.
Example of pseudocode for the algorthm
get the lastID [KP-0001]
remove some characters and put it in a variable [KP-]
convert the remaining into number since it's a string [0001]
increment by 1 [1 + 1 = 2]
convert it back to string and pad zero on the right [0002]
concatenate the variable and the newly incremented number [KP-0002]
save it.

I tried to do that in many ways but was unable to reach the solution... I also used triggers but that too didn't help me...
But I found a quick solution for that...
For example you want your employee to have employee codes 'emp101', 'emp102',...etc.
that too with an auto increment...
First of all create a table with three fields the first field containing the letters you want to have at the beginning i.e."emp", the second field containing the auto increasing numbers i.e 101,102,..etc., the third field containing both i.e 'emp101', 'emp102',...etc.
CREATE TABLE employee
(
empstr varchar( 5 ) default 'emp',
empno int( 5 ) AUTO_INCREMENT PRIMARY KEY ,
empcode varchar( 10 )
);
now providing an auto_increment value to empno.
ALTER TABLE employee AUTO_INCREMENT=101;
now coming to the topic... each time you insert values you have to concatenate the first two fields to get the values for the third field
INSERT INTO employee( empcode )
VALUES ('xyz');
UPDATE employee SET empcode = concat( empstr, empno ) ;

You can't auto increment varchar data type. Other way of doing this is to bifurcate varchar column into two different columns one will have integer part and other will have alphabet like in your case KP- once you auto increment all integer rows just concatenate these two columns

CREATE TABLE Customer (
CUSId INT NOT NULL IDENTITY(1, 1) PRIMARY KEY
,CUSKey AS 'Cus' + RIGHT('000' + CONVERT(VARCHAR(5), CUSId), 6) PERSISTED
,CusName VARCHAR(50)
,mobileno INT
,Gender VARCHAR(10)
)

Auto-increment is an integer, so adding text will not be possible.
Check out this question for other references.

Make a procedure, in my case MySQL.
CREATE PROCEDURE MOSTRAR_CODIGO_CLASE_PRODUCTO()
BEGIN
declare max varchar(10);
declare num int;
declare CCodigo varchar(10);
set max = (select MAX(Codigo_CP) from CLASE_PRODUCTO);
set num = (SELECT LTRIM(RIGHT(max,4)));
if num>=1 and num <=8 then
set num = num + 1;
set CCodigo = (select concat('CP000' , CAST(num as CHAR)));
elseif num>=9 and num <=98 then
set num = num + 1;
set CCodigo = (select concat('CP00' , CAST(num as CHAR)));
elseif num>=99 and num <=998 then
set num = num + 1;
set CCodigo = (select concat('CP0' , CAST(num as CHAR)));
elseif num>=999 and num <=9998 then
set num = num + 1;
set CCodigo = (select concat('CP' , CAST(num as CHAR)));
else
set CCodigo=(select 'CP0001');
end if;
SELECT MAX(CCodigo) AS Codigo_CP FROM CLASE_PRODUCTO;
END $
Java Class
public static boolean insertarClaseProducto(ClaseP cp){
boolean resp = false;
Connection cn;
Connection con = new Connection();
cn = con.connect();
try{
CallableStatement cs = cn.prepareCall("CALL REGISTRAR_CLASE_PRODUCTO (?)");
cs.setString(1, cp.getNombreCP());
int i = cs.executeUpdate();
if(i==1)
resp = true;
else
resp = false;
}catch(Exception e){System.out.println(e);}
return resp;
}
returns:
Codigo_MP Nombre_MP Estado_MP
MP0001 LG HAB
MP0002 GENIUS HAB
MP0003 MICRONICS HAB
MP0004 SONY HAB
MP0005 PANASONIC HAB

Related

MySQL user-defined function returns incorrect value when used in a SELECT statement

I met a problem when calling a user-defined function in MySQL. The computation is very simple but can't grasp where it went wrong and why it went wrong. Here's the thing.
So I created this function:
DELIMITER //
CREATE FUNCTION fn_computeLoanAmortization (_empId INT, _typeId INT)
RETURNS DECIMAL(17, 2)
BEGIN
SET #loanDeduction = 0.00;
SELECT TotalAmount, PeriodicDeduction, TotalInstallments, DeductionFlag
INTO #totalAmount, #periodicDeduction, #totalInstallments, #deductionFlag
FROM loans_table
WHERE TypeId = _typeId AND EmpId = _empId;
IF (#deductionFlag = 1) THEN
SET #remaining = #totalAmount - #totalInstallments;
IF(#remaining < #periodicDeduction) THEN
SET #loanDeduction = #remaining;
ELSE
SET #loanDeduction = #periodicDeduction;
END IF;
END IF;
RETURN #loanDeduction;
END;//
DELIMITER ;
If I call it like this, it works fine:
SELECT fn_computeLoanAmortization(3, 4)
But if I call it inside a SELECT statement, the result becomes erroneous:
SELECT Id, fn_computeLoanAmortization(Id, 4) AS Amort FROM emp_table
There's only one entry in the loans_table and the above statement should only result with one row having value in the Amort column but there are lots of random rows with the same Amort value as the one with the matching entry, which should not be the case.
Have anyone met this kind of weird dilemma? Or I might have done something wrong from my end. Kindly enlighten me.
Thank you very much.
EDIT:
By erroneous, I meant it like this:
loans_table has one record
EmpId = 1
TypeId = 2
PeriodicDeduction = 100
TotalAmount = 1000
TotalInstallments = 200
DeductionFlag = 1
emp_table has several rows
EmpId = 1
Name = Paolo
EmpId = 2
Name = Nikko
...
EmpId = 5
Name = Ariel
when I query the following statements, I get the correct value:
SELECT fn_computeLoanAmortization(1, 2)
SELECT Id, fn_computeLoanAmortization(Id, 2) AS Amort FROM emp_table WHERE EmpId = 1
But when I query this statement, I get incorrect values:
SELECT Id, fn_computeLoanAmortization(Id, 2) AS Amort FROM emp_table
Resultset would be:
EmpId | Amort
--------------------
1 | 100
2 | 100 (this should be 0, but the query returns 100)
3 | 100 (same error here)
...
5 | 100 (same error here up to the last record)
Inside your function, the variables you use to retrieve the values from the loans_table table are not local variables local to the function but session variables. When the select inside the function does not find any row, those variables still have the same values as from the previous execution of the function.
Use real local variables instead. In order to do that, use the variables names without # as a prefix and declare the variables at the beginning of the function. See this answer for more details.
I suspect the problem is that the variables in the INTO are not re-set when there is no matching row.
Just set them before the INTO:
BEGIN
SET #loanDeduction = 0.00;
SET #totalAmount = 0;
SET #periodicDeduction = 0;
SET #totalInstallments = 0;
SET #deductionFlag = 0;
SELECT TotalAmount, PeriodicDeduction, TotalInstallments, DeductionFlag
. . .
You might just want to set them to NULL.
Or, switch your logic to use local variables:
SET v_loanDeduction = 0.00;
SET v_totalAmount = 0;
SET v_periodicDeduction = 0;
SET v_totalInstallments = 0;
SET v_deductionFlag = 0;
And so on.

The conversion of the varchar value '6000545901' overflowed an int column

Begin
UPDATE pmptxft
SET
vaccno = (SELECT max(cast(isnull(vaccno,0) AS int)) + 1 FROM pmptxft WHERE iPRACID=#IPRACID)
WHERE ipatId = #PatientIdentity
END
Here vaccno datatype is varchar(max). Any Help in this regard will be appreciated.
I assume a datatype error is the cause. When you compare two values of a different datatype an automatic datatype conversion can cause such an error.
Check the datatypes of
the ipracis column and the #IPRACID variable
the ipatId column and the #PatientIdentity variable
The value 6000545901 is out of the range. The int data type has a range of:
-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)
Try using BIGINT instead:
UPDATE pmptxft
SET vaccno = (SELECT Max(Cast(Isnull(vaccno, 0) AS BIGINT)) + 1
FROM pmptxft
WHERE ipracid = #IPRACID)
WHERE ipatid = #PatientIdentity
Here's a working example.

Duplicate Entry Mysql Primary

Got some error within this code,
have tried to debug but couldn't find the answer.
Does anyone can correct me please?
BEGIN
DECLARE FINALID VARCHAR(8);
DECLARE MAXIDCOMPANY VARCHAR(8);
SELECT MAX(SUBSTRING(company.idCompany,3,8))+1 INTO MAXIDCOMPANY
FROM company
WHERE SUBSTRING(company.idCompany,1,2) = SUBSTRING(nmCompany,1,2);
IF MAXIDCOMPANY > 0 AND MAXIDCOMPANY < 10 THEN
SET FINALID = CONCAT(SUBSTRING(nmCompany,1,2),'00', CONVERT(MAXIDCOMPANY USING latin1));
ELSEIF MAXIDCOMPANY > 9 AND MAXIDCOMPANY < 100 THEN
SET FINALID = CONCAT(SUBSTRING(nmCompany,1,2),'0', CONVERT(MAXIDCOMPANY USING latin1));
ELSEIF MAXIDCOMPANY > 99 THEN
SET FINALID = CONCAT(SUBSTRING(nmCompany,1,2), CONVERT(MAXIDCOMPANY USING latin1));
END IF;
IF MAXIDCOMPANY IS NULL THEN
SET FINALID = CONCAT(SUBSTRING(nmCompany,1,2),'001');
END IF;
INSERT INTO company
(company.idCompany, company.nmCompany, company.country, company.address, company.region, company.joinDate, company.quota, company.createdUser, company.createdDate, company.updatedUser, company.updatedDate)
VALUES
(FINALID, nmCompany, country, address, region, joinDate, quota, createdUser, NOW(), updatedUser, updatedDate);
END
That's the code, the program stuck to counter after next to 1000.
EXAMPLE :
When I add the data for example IN1000 as the idCompany, it always stucks on that number, but when I query the maximum data it shows IN999 only, why not the IN1000
Huge thanks
Because the function max combine with SUB-STRING will return the maximum value within variable character, and the solution for this is substitute it with count function and the logic count will return the maximum value.
SELECT COUNT(company.idCompany) + 1 INTO MAXIDCOMPANY from company where SUBSTRING(company.idCompany,1,2) = SUBSTRING(company.idCompany,1,2);
based on my business proses, thank you all for the answer..

Mysql assign a single column value to a declared value using Select case

I am stucked with following issue,
I ve delcared a varibale (DOUBLE) in a stored procedure, and i need to assign a value (item price) from a table (item) to this declared variable. however, i need to get this value from a select query which uses case inside, the item price could be in 2 columns based on a logic i have to find the correct item price. Please help me solve this as when i execute it gives me a error,
Here how is layered,
DECLARE no_more_users INT DEFAULT 0;
DECLARE user_id INT DEFAULT 0;
DECLARE cart_id INT DEFAULT 0;
DECLARE cart_item_id INT DEFAULT 0;
DECLARE user_gift_id INT DEFAULT 0;
DECLARE itemPrice DOUBLE DEFAULT 0.0;
SELECT
CASE
WHEN sale_price=0 OR sale_price IS NULL THEN (price - ( price * discount ))
ELSE sale_price
END
INTO itemPrice
FROM item WHERE item_id = p_item_id ;
DECLARE checked_in_users CURSOR FOR
SELECT DISTINCT ul.user_id
FROM user_location ul
LEFT JOIN location_section ls ON ul.location_section_id = ls.location_section_id
INNER JOIN user u ON ul.user_id = u.user_id
INNER JOIN user_profile up ON u.user_id = up.user_id
INNER JOIN location_event le ON ul.location_event_id = le.location_event_id
WHERE ul.location_id = p_location_id AND ul.location_event_id = p_event_id
AND ul.checked_out_on IS NULL AND (ul.checked_in_on BETWEEN le.start_time AND le.end_time )
AND u.status = 1 ;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_users = 1;
OPEN checked_in_users;
FETCH checked_in_users INTO user_id;
read_loop: LOOP
some more code...
please note, sale_price, price, and discount are coulmns of item table, The logic is if sale_price is null or value is 0, then i actual sale price should be obtained from price coulmn. Finally what i need is asign corect item price in to previously declared varibale.
Any help will be highly appriciated.
There are two foms to the CASE statement, one with expressions and one with values. You are mixing them up.
with values:
CASE variable
WHEN value_1 THEN foo
WHEN value_2 THEN bar
END
with expressions:
CASE
WHEN expression_1 THEN foo
WHEN expression_2 THEN bar
END
Try
CASE
WHEN sale_price=0 OR sale_price IS NULL THEN (price - ( price * discount ))
ELSE sale_price
END
Also, you do not need the "AS correct_price" when you are using an INTO
Your select query has some problems.
The version of CASE you are are using - ie CASE var WHEN val1 THEN - doesn't work when trying to match a NILL, because in SQL null is not equal to null.
Also, you can't combine values with conditions as you hAve.
Instead, use the version if CASS that simply conditions. There are other suntactic problems. Converting your broken query then gives:
SELECT
CASE
WHEN ifnull(sale_price, 0) = 0 THEN price - (price * discount)
ELSE sale_price
END
INTO itemPrice
FROM item
WHERE item_id = p_item_id;
Note: if your table has s column called itemPrice, you must choose another name from your variable. Mysql gets confused :/

SQL: Auto Increment value during insert

I have the an existing table that for some reason the designer decided to manually control the Primary Key value by storing the last used value in a seperate table (changing the table to use Identity is not an option right now).
I now need to do a mass update to this table as follows:
DECLARE #NeedFieldID int
SET #NeedFieldID = 62034
INSERT INTO T_L_NeedField (NeedID, NeedFieldID, FieldName, Sequence, DisplayAs, FieldPrompt, DataType, ValidOptions, IsRequiredForSale)
(
SELECT
DISTINCT n.NeedID,
#NeedFieldID + 1,
'DetailedOutcome',
999,
'Detailed Outcome',
'Select appropriate reason for a No Sale outcome',
'T',
'Pricing, Appointment Date / Time Not Available, Will Call Back, Declined',
0
FROM T_L_Need n
INNER JOIN T_L_NeedField nf
ON n.NeedID = nf.NeedID
WHERE (n.Need LIKE 'Schedule%' AND n.Disabled = 0)
)
Obviously '#NeedFieldID + 1' doesn't work (just using it to show what I want to do). How can I increment #NeedFieldID as SQL inserts the values for each of the distinct NeedId's? I am using SQL Server 2008.
You want row_number():
DECLARE #NeedFieldID int
SET #NeedFieldID = 62034
INSERT INTO T_L_NeedField (NeedID, NeedFieldID, FieldName, Sequence, DisplayAs, FieldPrompt, DataType, ValidOptions, IsRequiredForSale)
(
SELECT
DISTINCT n.NeedID,
#NeedFieldID + row_number() over (order by n.NeedID),
'DetailedOutcome',
999,
'Detailed Outcome',
'Select appropriate reason for a No Sale outcome',
'T',
'Pricing, Appointment Date / Time Not Available, Will Call Back, Declined',
0
FROM T_L_Need n
INNER JOIN T_L_NeedField nf
ON n.NeedID = nf.NeedID
WHERE (n.Need LIKE 'Schedule%' AND n.Disabled = 0)
)
However, your best bet is to make NeedFieldID an identity column and just let SQL Server do the work for you.