0

我使用 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;
4

3 回答 3

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;
于 2013-11-04T12:20:20.537 回答
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;
于 2013-11-04T12:23:38.863 回答
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;
于 2013-11-04T12:14:22.480 回答