(PL \ SQL)Luhn支票号码生成

时间:2018-10-15 15:20:11

标签: plsql checksum luhn

如果我对一个数字序列进行Luhn公式检查,并且返回数字为0,则该数字序列有效(不是随机的)。我有一个随机数序列,但我需要一个Luhn数生成器,该生成器将返回一个数字。该数字应填写随机数序列,以将Luhn公式校验重新设置为0。

如何创建此Luhn编号生成器作为函数?

1 个答案:

答案 0 :(得分:0)

此结果适用于每个长度的数字序列。

CREATE OR REPLACE luhn_num (orig_num IN NUMBER)
RETURN STRING IS
  num_len NUMBER(20) := length(orig_num);
  result_num NUMBER(10);
  i NUMBER(10);
  temp_num NUMBER(10);
  sum_num NUMBER(10) := 0;

BEGIN
  IF MOD(num_len,2) = 0 THEN 
    FOR i IN 1..num_len LOOP
      IF MOD(i,2) = 0 THEN
        IF length(to_number(substr(orig_num,i,1))*2) > 1 THEN
          sum_num :=  sum_num + to_number(substr(to_number(substr(orig_num,i,1))*2,1,1)) + to_number(substr(to_number(substr(orig_num,i,1))*2,2,1));
        ELSE
          sum_num := sum_num + (to_number(substr(orig_num,i,1))*2);
        END IF;
      ELSE
        sum_num := sum_num + to_number(substr(orig_num,i,1));
      END IF;
    END LOOP;
  ELSE
    FOR i IN 1..num_len LOOP
      IF MOD(i,2) <> 0 THEN
        IF length(to_number(substr(orig_num,i,1))*2) > 1 THEN
          sum_num :=  sum_num + to_number(substr(to_number(substr(orig_num,i,1))*2,1,1)) + to_number(substr(to_number(substr(orig_num,i,1))*2,2,1));
        ELSE
          sum_num := sum_num + (to_number(substr(orig_num,i,1))*2);
        END IF;
      ELSE
        sum_num := sum_num + to_number(substr(orig_num,i,1));
      END IF;
    END LOOP;
  END IF;

  temp_num := 10 - to_number(substr(sum_num,length(sum_num),1));

  IF temp_num = 10 THEN
    result_num := 0;
  ELSE
    result_num := temp_num;
  END IF;

  RETURN result_num ;
END;