PL/SQL Check Digit, luhn using MOD 11

我只是一个虾纸丫 提交于 2019-12-12 01:39:36

问题


So here is the question: Write code to take in an id and determine if the check digit is correct

UPDATED CODE:

    Set SERVEROUTPUT ON
 DECLARE
      val_num NUMBER := '&user_input';
      holder NUMBER := 0;
      y NUMBER := 0;
      conv_string VARCHAR2(20);
   BEGIN
     conv_string := to_char(val_num*10);
     for x in 1..length(conv_string) loop
       y := to_number(substr(conv_string, -x, 1));
       if mod(x,2) = 0 then
         y := y * 2;
        if y > 9 then
         y := y - 9;
        end if;
       end if;
      holder := holder + y;
    end loop;
    dbms_output.put_line ('Check is '||(11-Mod(holder, 11)));
 END luhn;
   /
 SET SERVEROUTPUT ON

The return is:

SQL> @ loop
Enter value for user_input: 036532
old   2:       val_num NUMBER := '&user_input';
new   2:       val_num NUMBER := '036532';
Check is 2

It should be 6


回答1:


Before actual execution

SET SERVEROUTPUT ON

to enable SQL*Plus to fetch database output buffer.

Here is solution: https://community.oracle.com/thread/837639?start=0&tstart=0




回答2:


There are lots of different variations of the luhn algorithm, so looking at these implementations and your (I think incomplete) description in the comments I think this may be fairly close to what you are looking for, and gives the correct checksum for 036532 as per your initial question.

Hope it is helpfull

Set SERVEROUTPUT ON
 DECLARE
      val_num number := '036532';
      holder NUMBER := 0;
      y NUMBER := 0;
      conv_string VARCHAR2(20);
   BEGIN
     conv_string := to_char(val_num);
     FOR X IN 1..LENGTH(CONV_STRING) LOOP
       Y := TO_NUMBER(SUBSTR(CONV_STRING, -X, 1));
       IF ((X+1) > 10) THEN 
          Y := Y * 10;
       ELSE
          Y := Y * (X + 1);
       END IF;
       IF (Y >= 10) THEN 
          HOLDER := HOLDER + TO_NUMBER(substr(TO_CHAR(Y), 1, 1)) +  TO_NUMBER(substr(TO_CHAR(Y), 2, 1));
       ELSE
          HOLDER := HOLDER + Y;
       END IF;
     END LOOP;

         HOLDER :=  MOD(HOLDER, 11);
         Holder := 11 - mod(holder, 11);
     dbms_output.put_line ('Check is '|| holder);
 END luhn;
   /
 SET SERVEROUTPUT ON 


来源:https://stackoverflow.com/questions/34170104/pl-sql-check-digit-luhn-using-mod-11

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!