Last active
May 31, 2023 12:18
-
-
Save stevenmaguire/3f4b659d38101fe8092d to your computer and use it in GitHub Desktop.
MySQL function to convert ISBN10 to ISBN13
This file contains 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
DROP FUNCTION IF EXISTS `ISBN10to13`; | |
delimiter // | |
CREATE FUNCTION `ISBN10to13`(isbn10 VARCHAR(50)) RETURNS varchar(50) CHARSET utf8 | |
BEGIN | |
DECLARE isbn13 VARCHAR(13); | |
DECLARE i INT; | |
DECLARE chk INT; | |
IF (LENGTH(ISBN10) > 10) THEN | |
RETURN ISBN10; | |
ELSE | |
SET isbn10=SUBSTRING(ISBN10,1,10); | |
END IF; | |
# set ISBN10 = '0123456479'; | |
SET isbn13 = CONCAT('978' , LEFT(isbn10, 9)); | |
SET i = 1, chk = 0; | |
# 9*1+7*3+8*1=38 | |
SET chk = (38 + 3*LEFT(isbn10,1) | |
+ RIGHT(LEFT(isbn10,2),1) | |
+ 3*RIGHT(LEFT(isbn10,3),1) | |
+ RIGHT(LEFT(isbn10,4),1) | |
+ 3*RIGHT(LEFT(isbn10,5),1) | |
+ RIGHT(LEFT(isbn10,6),1) | |
+ 3*RIGHT(LEFT(isbn10,7),1) | |
+ RIGHT(LEFT(isbn10,8),1) | |
+ 3*LEFT(RIGHT(isbn10,2),1)); | |
SET chk = 10 - (chk % 10); | |
IF (chk<>10) then | |
SET isbn13 = concat(isbn13 , CONVERT(chk, CHAR(1))); | |
ELSE | |
SET isbn13 = concat(isbn13 , '0'); | |
END IF; | |
RETURN isbn13; | |
END // | |
delimiter ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment