初学者PL / SQL脚本。这段代码看起来是否正确?

时间:2014-05-15 07:59:01

标签: oracle plsql

我开始学习PL / SQL并且当前无法访问数据库(因此无法检查我的代码是否正确)。我正在尝试根据他们的身份证号码打印出学生的姓名。到目前为止,我有:

SET SERVEROUTPUT ON
DECLARE
  VNAME STUDENT.NAME%TYPE;
BEGIN
  SELECT NAME INTO VNAME
  FROM STUDENT
  WHERE ID = '0123';
  IF SQL%FOUND THEN
  DBMS_OUTPUT.PUT_LINE('Student with ID "0123" has the name ' || VNAME);
  END IF;
END;
/

语法看起来是否正确?它应该生成输出“ID为0123的学生名为____”

2 个答案:

答案 0 :(得分:2)

尝试使用异常处理程序,正如您在评论中指出的那样,您的IF无法按预期工作。

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/errors.htm#LNPLS856

SET SERVEROUTPUT ON
DECLARE
  VNAME STUDENT.NAME%TYPE;
BEGIN
 SELECT NAME INTO VNAME
 FROM STUDENT
 WHERE ID = ’0123’;
 DBMS_OUTPUT.PUT_LINE('Student with ID "0123" has the name ' || VNAME);
EXCEPTION
 WHEN NO_DATA_FOUND THEN
   DBMS_OUTPUT.PUT_LINE ('No student record found for that id '); 
END;
/

由于您无法访问数据库,因此以下是您原始脚本的功能:

DECLARE
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4

使用异常处理程序,在SQLPLUS中,您将获得:

No student record found for that id

PL/SQL procedure successfully completed.

SQL>

答案 1 :(得分:1)

如果您无权访问数据库,请尝试SQLFiddle。 您可以在线查看您的查询。