Luhn algorithm

Luhn algorithm can be used on Credit Card number verification stage.
So, probably, it could be usefull for somebody else.
Here is my implementation:

DELIMITER //
CREATE FUNCTION `LuhnCheck` (CC CHAR(19)) RETURNS BOOLEAN
BEGIN
  DECLARE i, mysum, r INT;
  DECLARE skip BOOLEAN;

  SET skip = TRUE;
  SET mysum = 0;

  SET i = CHAR_LENGTH(CC);

  WHILE i > 0 DO
    IF NOT skip THEN
      SET r = SUBSTRING(CC, i, 1) * 2;
      SET mysum = mysum + IF(r > 9, r - 9, r);
    ELSE
      SET mysum = mysum + SUBSTRING(CC, i, 1);
    END IF;

    SET i = i - 1;
    SET skip = NOT skip;
  END WHILE;

RETURN IF((MOD(mysum, 10) = 0) AND mysum <> 0, TRUE, FALSE);
END;
//
DELIMITER ;

More elegant solutions are welcome.

And here it is implemented with PLT Scheme.

4 Responses to “Luhn algorithm”

  1. on 10 Apr 2007 at 8:28 pm Jay Pipes

    Hi!

    This rocks! Be sure to add it to the MySQL Forge snippet repository. :)

    http://forge.mysql.com/snippets/

    Cheers!

    Jay

  2. on 11 Apr 2007 at 1:46 am Dmitri Mikhailov

    Client browser, application server are the right places for this checks.

  3. on 12 Apr 2007 at 8:45 am Arjen Lentz

    You don’t want to do this. See http://arjen-lentz.livejournal.com/88612.html

  4. on 13 Apr 2007 at 4:36 am Roland Bouman

    Hi!

    I’d say, my implementation is quite near yours:

    http://rpbouman.blogspot.com/2006/12/mysql-stored-routines-and-command-line.html

    Interestingly, I put up mine as a little contest to see who could guess what it does…I never got much response, but my intention was to reprint with inline code comments. So what do you think, does such a procedure deserve some comments? And…can you find the bug in my procedure?

    kind regards,

    Roland

Trackback this Post | Feed on comments to this Post

Leave a Reply