Tuesday, October 6th, 2009...7:27 am
Luhn Digit Generation Oracle PL/SQL Implementation
Here’s how to generate a Luhn Mod-10 Check Digit. It’s implemented as a function in oracle PL/SQL. I spent 2 hours looking for this online, then decided to implement it myself since it’s not that hard. Anyway, I thought I’d post it here for the next person trolling google for it. This is useful for generating credit card numbers or any other place you need a check digit.
This algorithm works by doing the same thing as the validation algorithm, but shifted over one character (the equivalent of adding a zero to a number, generating the sum & subtracting 10).
*EDIT – there was a bug in this code, i just fixed it on 12/4/2009, the old code returned 10 instead of zero. It also was only working on even numbers, sorry about that!
CREATE OR REPLACE FUNCTION generate_luhn (togen in varchar)
curval NUMBER := 0;
total NUMBER := 0;
everyother NUMBER := 1;
togen IS NULL
FOR i IN reverse 1 .. LENGTH(togen) loop
curval:=SUBSTR(togen, i, 1);
IF everyother = 1 then
everyother := 0;
curval := curval * 2;
IF(curval> 9) then
everyother := 1;
total := total + curval;
if MOD(total, 10) = 0 THEN
RETURN 10 – MOD(total, 10);