【问题标题】:PL/SQL - Numeric or Value ErrorPL/SQL - 数字或数值错误
【发布时间】:2023-03-09 23:57:01
【问题描述】:

Oracle 给我错误“ORA-06502: PL/SQL: numeric or value error: character to number conversion error ORA-06512: at line 15 06502. 00000 - “PL/SQL:数值或数值错误%s”

DECLARE
idnumber NUMBER(10);
initials VARCHAR2(100);
userid VARCHAR2(100);
old_initials VARCHAR2(100);
CURSOR cursor1 IS
SELECT  s_first, s_last FROM tst_student ORDER BY s_first;
student cursor1%ROWTYPE;
BEGIN
FOR student IN cursor1 LOOP
idnumber :=1;
old_initials := SUBSTR(student.s_first,1,1) || SUBSTR(student.s_last,1,1);
initials := SUBSTR(student.s_first,1,1) || SUBSTR(student.s_last,1,1);
IF initials = old_initials THEN
userid := old_initials || '00' || idnumber + 1;
ELSE idnumber := 1;
END IF;
DBMS_OUTPUT.PUT_LINE(userid);
END LOOP;
END;

它抱怨的那一行是 userid := old_initials || '00' ||身份证号码 + 1;

谢谢

【问题讨论】:

    标签: sql oracle plsql


    【解决方案1】:

    将该行更改为:

    userid := old_initials || '00' || (idnumber + 1); -- use brackets around the calculation
    


    问题是 Oracle 正在尝试将连接文本添加到数字 1,即 Oracle 将您的原始行解析为 userid := (old_initials || '00' || idnumber) + 1

    【讨论】:

    • 谢谢,这解决了我的错误,但它仍然没有增加我的价值。我试图让它为学生分配用户 ID。它只是将 001 分配给每个人。
    【解决方案2】:

    假设user_id是数字字段,使用to_number将字符串转换为数字为:

     userid := to_number(old_initials || '00' || (idnumber + 1));
    

    如果是varchar,输入,

     userid := old_initials || '00' || (idnumber + 1);
    

    编辑:递增,对于 NUMBER:

      idnumber := idnumber +1;
      userid := to_number(old_initials || '00' ||idnumber );
    

    对于 VARCHAR:

     idnumber := idnumber +1;
     userid := old_initials || '00' || idnumber + 1;
    

    EDIT1:更正的片段:

      idnumber :=1;
      old_initials := '';
      FOR student IN cursor1 LOOP
        initials := SUBSTR(student.s_first,1,1) || SUBSTR(student.s_last,1,1);
        IF initials = old_initials THEN
          idnumber := idnumber +1;
          userid := old_initials || '00' || idnumber;
         ELSE 
          idnumber := 1; 
          old_initials := initials;
        END IF;
        DBMS_OUTPUT.PUT_LINE(userid);
       END LOOP;
      END;
    

    【讨论】:

    • @user1834591 您不会在任何地方更改变量idnumber 的值。请参考更新后的答案。
    • 感谢您的帮助 Yogendra。由于某种原因,它仍然没有随着 idnumber 增加:= idnumber+1;也许我的其他代码不正确?
    • @user1834591:您在每次迭代中将idnumber1 分配到循环中。该语句应移出FOR 循环。请参考更新后的答案。
    • 效果很好!感谢您帮助 Yogendra!
    • @user1834591 代码中还有另一个错误。目前,old_initialsinitials 将始终相等,因此在首字母更改时不会重新编号。
    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多