【问题标题】:PLSQL - How to check &input is a numberPLSQL - 如何检查&输入是一个数字
【发布时间】:2017-03-22 13:15:32
【问题描述】:
DECLARE
  TEAM_ID NUMBER := &INPUT;
  CURSOR C_WORKER IS
  SELECT FIRST_NAME, LAST_NAME
  FROM EMPLOYEES
  WHERE DEPARTMENT_ID = TEAM_ID;
  V_LAST_NAME EMPLOYEES.LAST_NAME%TYPE;
  V_FIRST_NAME EMPLOYEES.FIRST_NAME%TYPE;
BEGIN
  OPEN C_WORKER;
    LOOP
      FETCH C_WORKER INTO V_LAST_NAME, V_FIRST_NAME;
      EXIT WHEN C_WORKER%NOTFOUND;
      DBMS_OUTPUT.PUT_LINE(V_LAST_NAME || ' ' || V_FIRST_NAME);
    END LOOP;
  CLOSE C_WORKER;
END;

如何更改此代码以检查 TEAM_ID(&input) 是否为数字? 如果是 - 打开光标,如果不是,打印“请写一个数字”。

最小值为 1,最大值为 TEAM_ID 的最大数量?或者它只是一个数字?

【问题讨论】:

  • 您将接受什么样的号码,以及采用何种格式?例如,带有千位分隔符的数字是否有效?和否定? ...请尝试更好地定义您需要获得帮助的检查
  • @Aleksej 我编辑帖子。好吗?
  • 目前还不清楚'1,000'是否应该算作数字。

标签: plsql sqlplus


【解决方案1】:

要处理替换变量,您需要将它们括在引号中并将它们视为字符串。

例如,这可能是一种满足您需要的方式:

declare
    -- define a varchar2 variable to host your variable; notice the quotes
    vStringInput        varchar2(10) := '&input';
    vNumInput           number;
    vVal                number;
    -- define a parametric cursor, to avoid references to variables
    cursor cur(num number) is select num from dual;
begin
    -- try to convert the string to a number
    begin
        vNumInput :=  to_number(vStringInput);
    exception
        when others then 
            vNumInput := null;
    end;
    --
    -- check the values, to understand if it is a number ( vNumInput NULL or NOT NULL)
    -- and, in case it's a number, if it suits your criteria
    case
        when vNumInput is null then 
            dbms_output.put_line('not a number');
        when vNumInput < 1 then 
            dbms_output.put_line('less than 1');
        -- whatever check you need on the numeric value
        else
            -- if the value is ok, open the cursor
            open cur(vNumInput); 
            loop
                fetch cur into vVal;                
                exit when cur%NOTFOUND;
                dbms_output.put_line('value from cursor: ' || vVal);
            end loop;            
    end case;    
end;
/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多