我在函数中有一个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;
答案 0 :(得分: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;
要查看无记录与 null值之间的区别,请参阅this sqlfiddle demo
答案 1 :(得分:1)
另一种解决方案,使用NVL / MAX而不是DISTINCT / Exception处理:
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;