我是PL / SQL的新手。尝试创建一个简单的代码,根据标记所在的范围分配等级。我的代码如下:
SET SERVEROUTPUT ON ;
ACCEPT N PROMPT 'ENTER NAME: ' ;
ACCEPT M PROMPT 'ENTER MARKS: ' ;
DECLARE
X CHAR ;
BEGIN
CASE TRUE
WHEN (M BETWEEN 0 AND 40) THEN X := 'E' ;
WHEN ((M>40)AND (M<=50)) THEN X := 'D' ;
WHEN ((M>50)AND (M<=60)) THEN X := 'C' ;
WHEN ((M>60)AND (M<=80)) THEN X := 'B' ;
WHEN ((M>80)AND (M<=100)) THEN X := 'A' ;
ELSE X := 'Z' ;
END CASE ;
IF(X = Z) THEN
DBMS_OUTPUT.PUT_LINE('ERROR!!!! MARKS NOT IN RANGE');
ELSE
DBMS_OUTPUT.PUT_LINE(N || ' HAVING GRADE ' || X);
END IF;
END;
/
我尝试运行时遇到以下错误:
ENTER NAME: D
ENTER MARKS: 300
WHEN (M BETWEEN 0 AND 40) THEN X := 'E' ;
*
ERROR at line 5:
ORA-06550: line 5, column 7:
PLS-00201: identifier 'M' must be declared
ORA-06550: line 4, column 1:
PL/SQL: Statement ignored
ORA-06550: line 12, column 8:
PLS-00306: wrong number or types of arguments in call to 'Z'
ORA-06550: line 12, column 1:
PL/SQL: Statement ignored
我哪里错了?我使用提示输入M的值,为什么不使用它?
答案 0 :(得分:1)
您的CASE语句没有语法错误。您会收到错误,因为您需要将输入作为替换变量引用。 ACCEPT是一个SQL * Plus plus命令,用于从用户获取值。在代码本身中,替换变量必须以&符号为前缀。当我们运行代码时,SQL * Plus客户端将在替换变量的每个实例处注入输入值。
有两点需要注意:
&M
经常引用变量时,这非常烦人。使用SQL * Plus命令set verify off
抑制此行为。以下是修复了替换变量的代码。
DECLARE
X CHAR ;
BEGIN
CASE TRUE
WHEN (&M BETWEEN 0 AND 40) THEN X := 'E' ;
WHEN ((&M>40)AND (&M<=50)) THEN X := 'D' ;
WHEN ((&M>50)AND (&M<=60)) THEN X := 'C' ;
WHEN ((&M>60)AND (&M<=80)) THEN X := 'B' ;
WHEN ((&M>80)AND (&M<=100)) THEN X := 'A' ;
ELSE
X := 'Z' ;
END CASE ;
IF(X = 'Z') THEN
DBMS_OUTPUT.PUT_LINE('ERROR!!!! MARKS NOT IN RANGE');
ELSE
DBMS_OUTPUT.PUT_LINE('&N' || ' HAVING GRADE ' || X);
END IF;
END;
/
答案 1 :(得分:0)
ACCEPT
读取一行输入并将其存储在替换变量中。如果要使用替换变量,请使用&variable_name
。您也无法在CASE
语句中分配变量:
SET SERVEROUTPUT ON ;
ACCEPT N CHAR PROMPT 'ENTER NAME: ';
ACCEPT M NUMBER PROMPT 'ENTER MARKS: ';
DECLARE
X CHAR(1) := CASE
WHEN &M BETWEEN 0 AND 40 THEN 'E'
WHEN &M BETWEEN 40 AND 50 THEN 'D'
WHEN &M BETWEEN 50 AND 60 THEN 'C'
WHEN &M BETWEEN 60 AND 80 THEN 'B'
WHEN &M BETWEEN 80 AND 100 THEN 'A'
ELSE 'Z'
END;
BEGIN
IF X = 'Z' THEN
DBMS_OUTPUT.PUT_LINE('ERROR!!!! MARKS NOT IN RANGE');
ELSE
DBMS_OUTPUT.PUT_LINE( '&N HAVING GRADE ' || X);
END IF;
END;
/