跳过PL / SQL Oracle数据库中的错误

时间:2013-11-04 12:07:49

标签: sql database oracle plsql

我使用Oracle PL / SQL并且需要检查表中是否有ID的客户端。 (是还是不是)。我对表进行了查询,它将带有此ID的行返回到v_klient。例如,在我的表中没有编号为2的ID。但我无法比较这一点,因为错误“找不到数据”。需要跳过此错误并与if语句进行比较,并执行一些我想要的操作。

DECLARE
    id_kl_original  NUMBER := 2; // this ID
    v_klient klients%rowtype; // Variable for query return
BEGIN
SELECT *
  INTO  v_klient
    FROM klients
      WHERE id_klient=id_kl_original; // query

IF (v_klient IS NULL) THEN
     DBMS_OUTPUT.put_line(' There's no clients with this ID.');
     /* SOME ACTIONS*/
ELSE
    DBMS_OUTPUT.put_line(v_klient.id_klient);
    /* SOME ACTIONS*/
END IF;

END;

3 个答案:

答案 0 :(得分:4)

你可以这样试试:

DECLARE
    id_kl_original  NUMBER := 2; // this ID
    v_klient klients%rowtype; // Variable for query return
BEGIN
   BEGIN
      SELECT *
      INTO  v_klient
      FROM klients
      WHERE id_klient=id_kl_original; // query

      DBMS_OUTPUT.put_line(v_klient.id_klient);
      /* SOME ACTIONS*/
   EXCEPTION WHEN NO_DATA_FOUND
     DBMS_OUTPUT.put_line(' There's no clients with this ID.');
     /* SOME ACTIONS*/
   END;
   /* REST OF PROCEDURE */
END;

答案 1 :(得分:0)

这将有效:

DECLARE
    id_kl_original  NUMBER := 2; // this ID
    i NUMBER; // Variable for query return
BEGIN
SELECT count(*)
  INTO i
    FROM klients
      WHERE id_klient=id_kl_original; // query

IF (i = 0) THEN
     DBMS_OUTPUT.put_line(' There are no clients with this ID.');
     /* SOME ACTIONS*/
ELSE
    DBMS_OUTPUT.put_line(v_klient.id_klient);
    /* SOME ACTIONS*/
END IF;

END;

答案 2 :(得分:0)

使用no_data_found异常比首先执行查询以获取行数然后再次执行以实际获取行更简洁。

DECLARE
    id_kl_original  NUMBER := 2; -- this ID
    v_klient klients%rowtype; -- Variable for query return
    v_has_data := true;
BEGIN

    BEGIN
        SELECT *
          INTO  v_klient
            FROM klients
              WHERE id_klient = id_kl_original; -- query
    EXCEPTION
        WHEN NO_DATA_FOUND THEN 
            v_has_data := FALSE; 
    END;

    IF v_has_data = FALSE THEN
         DBMS_OUTPUT.put_line('There''s no clients with this ID.');
         /* SOME ACTIONS */
    ELSE
        DBMS_OUTPUT.put_line(v_klient.id_klient);
        /* SOME ACTIONS*/
    END IF;

END;