PL/SQL: how do i prompt user input in a procedure?

前端 未结 4 2000
渐次进展
渐次进展 2020-12-09 23:26

This is a question about a small part of a large project I\'m doing. I tried the following but I just get the two errors below it:

SET SERVEROUTPUT ON

CREAT         


        
相关标签:
4条回答
  • 2020-12-10 00:02

    This piece of code works only in SQL*Plus and can't be used to produce a stored procedure!!!

    DECLARE
    variable1 NUMBER(1);
    variable2 CHAR(1);
    
    BEGIN
    DBMS_OUTPUT.PUT_LINE('Hello World');
    variable1 := &please_enter_1_or_0;
    variable2 := '&please_enter_y_or_n';
    END;
    

    Mind the difference in the last statement where the last substitution variable is quoted in a string to be properly accepted by the PL/SQL syntax. Anyway, as I told you in the last comment to your question this is not a user interaction but just the result of a statement preprocessing. Every time you input different values the RDBMS executes a different source code.

    Probably your requirement to use a "procedure" doesn't meant to use a STORED procedure(that is impossible to do so), but they just intended a SQL*Plus script, ask for clarifications.

    0 讨论(0)
  • 2020-12-10 00:06

    You can just Remove the declare to remedy that ora error

    0 讨论(0)
  • 2020-12-10 00:14

    PL/SQL is a language for writing autonomous programs. It is not designed for user interactivity. Input values are passed as parameters. So your program should look like this

    CREATE OR REPLACE PROCEDURE HELLO
        (p1 in number
          , p2 in varchar2)
    AS
        l_salutation varchar2(20) := 'Hello World';
    BEGIN
        DBMS_OUTPUT.PUT_LINE(l_salutation);
        DBMS_OUTPUT.PUT_LINE('p1 = ' || p1);
        DBMS_OUTPUT.PUT_LINE('p2 = ' || p2);
    END;
    /
    

    Note there is no need for DECLARE with a named Procedure. The section between AS and BEGIN is for declaring variables, as I've done with l_salutation.

    You can provide values for those parameters when invoking the program. In SQL*Plus it would work like this:

    SET SERVEROUTPUT ON
    
    accept p1 prompt "please enter 1 or 0: "
    accept p2 prompt "please enter Y or N: "
    
    exec HELLO (:p1, :p2)
    
    0 讨论(0)
  • 2020-12-10 00:22

    You cannot directly receive messages from the client in a PL/SQL procedure or package.

    The best you can do to emulate this is to interface with table data, and have users insert data into the table and react to that, or use Advanced Queueing (which amounts to pretty much the same thing).

    Alternatively, accept the user input as parameters when the procedure is called.

    0 讨论(0)
提交回复
热议问题