0

我在函数中有一个 sql 查询

SELECT  DISTINCT (product_id)
      INTO  prod
      FROM  products
     WHERE       mfg_no = 'TEL'             
                AND status = p_status

有时 product_id 为 null 或 p_status 没有数据。因为这个函数不返回任何值。

我尝试了 nvl、decode 和 case 语句来检查 product_id,但没有一个不起作用。即使 product_id 为 null 或为空,如何确保我的函数正常执行?

我试图在 EXCEPTION 块中返回一个值,如下所示,这也无济于事。

EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
        prod := 'NA';

编辑 1

CREATE OR REPLACE FUNCTION my_function (p_status VARCHAR2)
    RETURN VARCHAR2
AS
    prod     VARCHAR2 (2000);
BEGIN
    prod := NULL;  


    SELECT  DISTINCT (product_id)
      INTO  prod
      FROM  products
     WHERE  mfg_no = 'TEL' AND status = p_status;

    RETURN prod;
EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
        prod := 'N/A';
        DBMS_OUTPUT.put_line ('no data found ' || SQLERRM);
    WHEN OTHERS
    THEN
        DBMS_OUTPUT.put_line ('error ' || SQLERRM);
        prod := 'N/A';
END;
4

2 回答 2

1

试试这样:

CREATE OR REPLACE FUNCTION my_function (p_status VARCHAR2)
    RETURN VARCHAR2
AS
    prod     VARCHAR2 (2000);
BEGIN
    prod := NULL;

  BEGIN
    SELECT  DISTINCT (product_id)
      INTO  prod
      FROM  products
     WHERE  mfg_no = 'TEL' AND status = p_status;

  EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
        prod := 'N/A';
        DBMS_OUTPUT.put_line ('no data found ' || SQLERRM);
    WHEN OTHERS
    THEN
        DBMS_OUTPUT.put_line ('error ' || SQLERRM);
        prod := 'N/A';
  END;

  RETURN prod;

END;

要查看无记录空值之间的区别,请参阅此 sqlfiddle 演示

于 2012-12-03T13:29:40.340 回答
1

另一种解决方案,使用 NVL / MAX 而不是 DISTINCT / 异常处理:

CREATE OR REPLACE FUNCTION my_function (p_status VARCHAR2)
    RETURN VARCHAR2
AS
    prod     VARCHAR2 (2000);
BEGIN
    SELECT  NVL(MAX(product_id), 'N/A')
      INTO  prod
      FROM  products
     WHERE  mfg_no = 'TEL' AND status = p_status;
  RETURN prod;

END;
于 2012-12-03T13:50:13.983 回答