Tuesday, October 6th, 2009...7:27 am

Luhn Digit Generation Oracle PL/SQL Implementation

Jump to Comments

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!

[sql]
CREATE OR REPLACE FUNCTION generate_luhn (togen in varchar)
RETURN number
IS
curval NUMBER := 0;
total NUMBER := 0;
everyother NUMBER := 1;

BEGIN
IF(
togen IS NULL
) then
RETURN 0;
end IF;

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
curval:=curval-9;
end IF;
else
everyother := 1;
end IF;

total := total + curval;
end loop;
if MOD(total, 10) = 0 THEN
RETURN 0;
ELSE
RETURN 10 – MOD(total, 10);
END IF;
END generate_luhn;
/
[/sql]

7 Comments

Leave a Reply