Skip to content

Instantly share code, notes, and snippets.

@Den2016
Created June 3, 2020 07:38
Show Gist options
  • Save Den2016/2b1f6e1badc97bbc58e8e424766fe437 to your computer and use it in GitHub Desktop.
Save Den2016/2b1f6e1badc97bbc58e8e424766fe437 to your computer and use it in GitHub Desktop.
MySQL stored function to generate EAN13 from INT
CREATE FUNCTION `GEN_EAN13`(
`CODE` INT
)
RETURNS VARCHAR(13)
LANGUAGE SQL
NOT DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE response VARCHAR(13);
DECLARE prefix CHAR(2);
DECLARE indx INT;
DECLARE SumODD INT;
DECLARE SumEven INT;
DECLARE Summ INT;
SET prefix = '24'; /* first two digits in generated barcode */
SET response = CAST(CODE as varchar(13));
WHILE LENGTH(response)<12-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 > 0 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 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