将值放入NUMBER变量时出错

时间:2017-02-03 04:00:05

标签: sql oracle plsql

我有以下PL / SQL块:

DECLARE
  proj_ID VARCHAR2(5):=500;
  proj_name VARCHAR2(30); 
  pledge_count VARCHAR2(15);
  pledge_sum NUMBER(7,2);
  pledge_avg NUMBER(7,2);
BEGIN
  SELECT projname
    INTO proj_name
    FROM dd_project
    WHERE idproj = proj_ID;

  SELECT COUNT(idproj)
    INTO pledge_count
    FROM dd_pledge
    WHERE idproj = proj_ID;

  SELECT TO_CHAR(SUM(pledgeamt), '$999.99')
    INTO pledge_sum
    FROM dd_pledge
    WHERE idproj = proj_ID;

    SELECT TO_CHAR(AVG(pledgeamt), '$999.99')
      INTO pledge_avg
      FROM dd_pledge
      WHERE idproj = proj_ID;

  DBMS_OUTPUT.PUT_LINE('Project ID: ' || proj_ID || ' Project Name: ' || proj_name || 'Pledge Count: ' || pledge_count
  || ' Total Dollars Pledged: ' || pledge_sum || ' Avg. Pledge Amount: ' || pledge_avg);
END;

我收到Oracle错误,说我有算术问题,而且我可能会尝试将值存储到一个不够大的变量中。我感到很困惑,因为我的SUM变量值最终为$ 190.00,而我的AVG变量值最终为$ 63.33(我已在单独的SELECT语句中确认)。我的声明的pledge_sum和pledge_avg变量是否足以存储精度为7且​​标度为2的那些值? NUMBER(7,2)是否应该保持一个大到99,999.99美元的价值?

当您使用NUMBER数据类型时,我不明白吗?或者我的精确度和规模究竟是什么意思?

任何帮助都会很棒。感谢

1 个答案:

答案 0 :(得分:0)

TO_CHAR(col, '$999.99')

以上格式化从col到string的值并添加货币字符。

因此,何时尝试将此值转换为数字变量,您将获得

  

PL / SQL:数字或值错误:字符到数字转换错误

因为to_char生成的字符串不能隐式转换为数字。

您可能想要使用varchar2

pledge_sum varchar2(20);
pledge_avg varchar2(20);

或在末尾对变量使用to_char。

DECLARE
  proj_ID VARCHAR2(5):=500;
  proj_name VARCHAR2(30); 
  pledge_count VARCHAR2(15);
  pledge_sum NUMBER(7,2);
  pledge_avg NUMBER(7,2);
BEGIN
  SELECT projname
    INTO proj_name
    FROM dd_project
    WHERE idproj = proj_ID;

  SELECT COUNT(idproj)
    INTO pledge_count
    FROM dd_pledge
    WHERE idproj = proj_ID;

  SELECT SUM(pledgeamt)
    INTO pledge_sum
    FROM dd_pledge
    WHERE idproj = proj_ID;

    SELECT AVG(pledgeamt)
      INTO pledge_avg
      FROM dd_pledge
      WHERE idproj = proj_ID;

  DBMS_OUTPUT.PUT_LINE('Project ID: ' || proj_ID || ' Project Name: ' || proj_name || 'Pledge Count: ' || pledge_count
  || ' Total Dollars Pledged: ' || to_char(pledge_sum, '$999.99') || ' Avg. Pledge Amount: ' || to_char(pledge_avg, '$999.99'));
END;