plpgsql函数:从根据随机表创建的视图返回行 [英] plpgsql function: Return rows from a view created from random table

查看:88
本文介绍了plpgsql函数:从根据随机表创建的视图返回行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,该函数从一个未知表创建的视图中返回行:

I want to create a function that returns rows from a view created from a unknown table(s):

    CREATE OR REPLACE FUNCTION tt_query(text, timestamp without time zone)
      RETURNS SETOF record AS
    $$
    DECLARE

    orig_name ALIAS FOR $1;
    data_tt ALIAS FOR $2;

    BEGIN

    [...]

    EXECUTE 'create OR REPLACE TEMP view temp as 
    select * 
    from  '
    ||orig_name 
    ||' where trigger_changed >'
    ||quote_literal(data_tt)
    ||' ORDER BY trigger_changed DESC';

    [...]--other work on view temp

    --NOW I WANT RETURN THE ROW OF view temp
    END;
    $$
    LANGUAGE plpgsql VOLATILE

好吧,我已经想到(在您的帮助下):

ok I have think (with yours help) this:

表格:

create table t(a integer, b text);

功能:

CREATE OR REPLACE FUNCTION f()
  RETURNS SETOF record AS
$$
BEGIN

RETURN QUERY EXECUTE 'SELECT * FROM t';

END;
  $$
  LANGUAGE plpgsql VOLATILE

类型:

CREATE TYPE y AS (
    a int,
    b text
);

现在有可能吗?:

select * from f() as y;

在我的情况下,

y名称是一个变量,我在另一个函数中创建了它

y name in my case is a variable an I create it in an other function

推荐答案

它可以像这样工作:

CREATE OR REPLACE FUNCTION tt_query(orig_name regclass, data_tt timestamp)
  RETURNS SETOF record AS
$func$
BEGIN

EXECUTE 'CREATE OR REPLACE TEMP VIEW tmp as 
select * 
from  '
|| orig_name 
|| ' where trigger_changed >'
|| quote_literal(data_tt)
|| ' ORDER BY trigger_changed DESC';

-- other work on view tmp

-- return the rows of view temp
RETURN QUERY
SELECT * FROM tmp;

END
$func$  LANGUAGE plpgsql;

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆