dsnnvpobaljihv3490 2014-10-23 10:02
浏览 372
已采纳

如何不返回从存储过程中找到的记录

Is it possible to have a stored procedure behave exactly like a regular select query when no records are found, or is this a driver issue.

For example, with go, a query that returns no rows will return an sql.ErrNoRows error. However, this will not:

create table emptytable(id int);

create function selectany() returns emptytable as $$
DECLARE
  _out emptytable;
BEGIN
  SELECT * INTO emptytable FROM emptytable limit 1;
  RETURN _out;
END;
$$ LANGUAGE PLPGSQL;

I have tried SELECT INTO STRICT, and while that raises a "query returned no rows" error, it is not the same as a non-stored procedure query. Neither is raising NO_DATA_FOUND.

  • 写回答

3条回答 默认 最新

  • douxian3828 2014-10-30 15:59
    关注

    If I understand your requirements correctly:

    Return one or no row from a function and allow to do more with the returned row (if any).

    Test table:

    CREATE TABLE emptytable(id int, txt text);  -- multiple columns
    

    To return one or no complete table row:

    CREATE OR REPLACE FUNCTION selectany_all()
      RETURNS SETOF emptytable AS
    $func$
    DECLARE
       _out  emptytable;
    BEGIN
       FOR _out IN
          SELECT * FROM emptytable LIMIT 1
       LOOP
         -- do something with _out before returning
         RAISE NOTICE 'before: %', _out;
         RETURN NEXT _out;
         -- or do something with _out after returning row
         RAISE NOTICE 'after: %', _out;
       END LOOP;
    END
    $func$ LANGUAGE plpgsql;
    

    For a more flexible approach: return arbitrary columns:

    CREATE OR REPLACE FUNCTION selectany_any()
      RETURNS TABLE (id int, txt text) AS
    $func$
    BEGIN
       FOR id, txt IN
          SELECT e.id, e.txt FROM emptytable e LIMIT 1
       LOOP  
         -- do something with id and text before returning
         RAISE NOTICE 'before: %, %', id, txt;
         RETURN NEXT;
         -- or do something with id and text after returning row
         RAISE NOTICE 'after: %, %', id, txt;
       END LOOP;
    END
    $func$ LANGUAGE plpgsql;
    

    Note, the LOOP is never entered if there is no row. Accordingly you will get no NOTICE from my test code.

    Both functions work for n rows returned as well, LIMIT 1 is just for this particular request.

    Closely related, wtih more explanation:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源