Created
June 12, 2020 09:31
-
-
Save Den2016/a4cd0f2f2589a923abbbacde4f33a498 to your computer and use it in GitHub Desktop.
MySQL stored procedure to generate EAN8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE DEFINER=`root`@`%` FUNCTION `GEN_EAN8`( | |
`CODE` INT | |
) | |
RETURNS vARCHAR(8) | |
LANGUAGE SQL | |
NOT DETERMINISTIC | |
NO SQL | |
SQL SECURITY DEFINER | |
COMMENT '' | |
BEGIN | |
DECLARE response VARCHAR(8); | |
DECLARE prefix CHAR(1); | |
DECLARE indx INT; | |
DECLARE SumODD INT; | |
DECLARE SumEven INT; | |
DECLARE Summ INT; | |
SET prefix = '2'; | |
SET response = CAST(CODE as varchar(8)); | |
WHILE LENGTH(response)<7-LENGTH(prefix) DO | |
SET response = CONCAT('0',response); | |
END WHILE; | |
SET response = CONCAT(prefix,response); | |
SET indx = LENGTH(response); | |
SET SumODD = 0; | |
SET SumEven = 0; | |
WHILE indx > 2 DO | |
SET SumODD = SumODD+CAST(SUBSTRING(response,indx,1) AS INT); | |
SET indx = indx-1; | |
SET SumEven = SumEven+CAST(SUBSTRING(response,indx,1) AS INT); | |
SET indx = indx-1; | |
END WHILE; | |
SET SumODD = SumODD+CAST(SUBSTRING(response,indx,1) AS INT); | |
SET Summ = SumODD * 3 + SumEven; | |
SET indx = CASE Summ % 10 | |
WHEN 0 THEN '0' | |
ELSE 10 - Summ % 10 | |
END; | |
SET response = CONCAT(response,CAST(indx AS VARCHAR(1))); | |
RETURN(response); | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment