当我在plsql中编写if else条件来检查是否使用if conditopn时是偶数还是奇数时,请帮助你。如果我输入字符然后它将引发一个错误。如何使用异常来理解客户端。帮助我
declare
num number:=&number;
begin
if num=1 then
dbms_output.put_line('composite');
else if mod(num,2)=0 then
dbms_output.put_line('even');
else if mod(num,2)=1 then
dbms_output.put_line('odd');
else
dbms_output.put_line('enter proper data');
end if;
end if;
end if;
end;
/
答案 0 :(得分:0)
请参阅以下工作示例:
declare
-- user input is always a string so treat it as a string
v_input varchar2(32767) := '&number';
num number;
begin
-- convert input to a number. to_number() throws if input string can't be
-- converted to a number. see to_number() documentation for details.
-- the conversion has to happen inside begin-end block because the exception
-- handler of the block won't catch exceptions raised in declare block.
num:=to_number(v_input);
-- do your math
if num=1 then
dbms_output.put_line('composite');
elsif mod(num,2)=0 then
dbms_output.put_line('even');
elsif mod(num,2)=1 then
dbms_output.put_line('odd');
else
dbms_output.put_line('enter proper data');
end if;
exception
-- the exception raised by to_number()
when value_error then
dbms_output.put_line('not a valid number: ' || v_input);
-- all other exceptions are still raised to the caller.
end;
/
示例结果:
SQL> @so
Enter value for number: 1
old 2: v_input varchar2(32767) := '&number';
new 2: v_input varchar2(32767) := '1';
composite
PL/SQL procedure successfully completed.
SQL> @so
Enter value for number: 2
old 2: v_input varchar2(32767) := '&number';
new 2: v_input varchar2(32767) := '2';
even
PL/SQL procedure successfully completed.
SQL> @so
Enter value for number: 3
old 2: v_input varchar2(32767) := '&number';
new 2: v_input varchar2(32767) := '3';
odd
PL/SQL procedure successfully completed.
SQL> @so
Enter value for number: foo
old 2: v_input varchar2(32767) := '&number';
new 2: v_input varchar2(32767) := 'foo';
not a valid number: foo
PL/SQL procedure successfully completed.
SQL>