如何让用户输入另一个值,直到用户在plsql中只输入正数

时间:2018-06-10 18:18:17

标签: plsql plsqldeveloper

CREATE OR REPLACE PROCEDURE findSquareRoot 
 ( v_num in NUMBER)
  is negative_Number Exception; 
BEGIN
    if(v_num<0) then
        RAISE negative_Number;
    else
        DBMS_OUTPUT.PUT_LINE ('Square root of '||v_num||' is'||SQRT(v_num));
    end if;
EXCEPTION
 WHEN negative_Number THEN
      RAISE_APPLICATION_ERROR(-20989,'Please provide a valid number');
END;

使用循环测试块

DECLARE
  lv_input  NUMBER;
BEGIN
   LOOP
       lv_input := &num
       findSquareRoot(lv_input);
       EXIT WHEN lv_input > 0;
   END LOOP;
end;

即使我提到它只应在输入大于零时才退出,但Loop只执行一次。

2 个答案:

答案 0 :(得分:0)

在您的逻辑中 - procedure findSquareRoot没有返回值 结果是例外;

CREATE OR REPLACE PROCEDURE findSquareRoot 
 ( v_num in out NUMBER)

    BEGIN
        if(v_num<0) then
            v_num:=0;
        else
            v_num:=1;
        end if;
    EXCEPTION
     WHEN others THEN
          dbms_outout.put_line(sqlcode);
    END;

答案 1 :(得分:0)

正如你所知,PL / SQL在这里无法帮助。

如果您使用的是MS Windows,则可以使用简单的批处理脚本执行此操作。这是怎么回事。

  • 批处理脚本将要求用户输入一个值,并将继续这样做,直到输入正数
  • 一旦满足上述条件,它就运行SQL * Plus并调用运行该过程的.SQL脚本,传递用户已输入的参数

以下是脚本:

<强> SQROOT.BAT

@echo off
:repeat
set /p numb="Enter a positive number : "
if %numb% lss 0 goto :repeat
sqlplus scott/tiger@orcl @sqroot %numb%

<强> SQROOT.SQL

set serveroutput on
exec findSquareRoot(&1)

您的程序

CREATE OR REPLACE PROCEDURE findsquareroot (v_num IN NUMBER)
IS
   negative_number   EXCEPTION;
BEGIN
   IF (v_num < 0)
   THEN
      RAISE negative_number;
   ELSE
      DBMS_OUTPUT.put_line (
         'Square root of ' || v_num || ' is ' || SQRT (v_num));
   END IF;
EXCEPTION
   WHEN negative_number
   THEN
      raise_application_error (-20989, 'Please provide a valid number');
END;
/

<强>测试

M:\>sqroot
Enter a positive number : -2
Enter a positive number : 25

SQL*Plus: Release 11.2.0.1.0 Production on Pon Lip 11 08:35:47 2018

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options

Square root of 25 is 5

PL/SQL procedure successfully completed.

SQL>

这不是完美的,可以/应该改进,但是 - 为了快速说明,我希望你有这个想法。