【问题标题】:returning a query result from dynamic query从动态查询返回查询结果
【发布时间】:2018-05-11 16:09:57
【问题描述】:

阅读有关如何制作返回查询结果的 SP 似乎我必须做这种事情(来自教程网站)

CREATE OR REPLACE FUNCTION show_cities() RETURNS refcursor AS $$
    DECLARE
      ref refcursor;                                                     -- Declare a cursor variable
    BEGIN
      OPEN ref FOR SELECT city, state FROM cities;   -- Open a cursor
      RETURN ref;                                                       -- Return the cursor to the caller
    END;
    $$ LANGUAGE plpgsql;

好的,我明白了,但我想将 SQL 作为参数传递,所以我需要这样做(我认为)

EXECUTE mysql ......

但我不知道如何让EXECUTE 返回光标

编辑: 好的,现在我发现我误解了非动态案例的作用。我希望能够做到select show_cities() 并让它做与SELECT city, state FROM cities 相同的事情,但事实并非如此。当然,现在想想,这并不奇怪。我想返回实际的记录集。

【问题讨论】:

标签: postgresql plpgsql


【解决方案1】:

你的情况是这样的:

t=# CREATE OR REPLACE FUNCTION data_of(_tbl_type anyelement)
  RETURNS SETOF anyelement AS
$func$
BEGIN
   RETURN QUERY EXECUTE format('
      SELECT *
      FROM   %s  -- pg_typeof returns regtype, quoted automatically
      WHERE  true /*or some filter in additional arguments or so */
      ORDER  BY true /*or some filter in additional arguments or so */'
    , pg_typeof(_tbl_type))
   ;
END
$func$ LANGUAGE plpgsql;
CREATE FUNCTION

会起作用:

t=# create table city(i serial, cn text);
CREATE TABLE
t=# insert into city(cn) values ('Moscow'), ('Barcelona'),('Visaginas');
INSERT 0 3
t=# SELECT * FROM data_of(NULL::city);
 i |    cn
---+-----------
 1 | Moscow
 2 | Barcelona
 3 | Visaginas
(3 rows)

所有归功于 Erwin 的 https://stackoverflow.com/a/11751557/5315974 是必读的内容

【讨论】:

    猜你喜欢
    • 2018-12-29
    • 1970-01-01
    • 2013-10-01
    • 2013-08-24
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多