plpgsql如何在函数或过程中执行查询

时间:2013-05-23 20:03:16

标签: sql postgresql plpgsql

我开始在postgres数据库中学习sql中的存储过程和函数。 我需要一个例子来帮助我实现我想要完成的目标。

我需要运行一个程序并让它返回结果。例如:

run_query(name):
 begin
 return select * from employees where first_name = $name
 end
end

我想在运行它时返回结果集。这可能吗?提前谢谢你的帮助! 这是我试图创建的函数:

CREATE OR REPLACE FUNCTION test() RETURNS TABLE(id INT, subdomain varchar, launched_on_xxx timestamp, UVs bigint, PVs bigint) AS
  'SELECT dblink_connect(''other_DB'');
  SELECT    c.id as id, c.subdomain, c.launched_on_xxx, COALESCE(SUM(tbd.new_unique_visitors), 0) AS UVs, COALESCE(SUM(tbd.page_views), 0) AS PVs
    FROM    dblink(''SELECT id, subdomain, launched_on_xxx FROM communities'')
            AS c(id int, subdomain character varying, launched_on_xxx timestamp)
        LEFT OUTER JOIN days_of_center tbd
            ON  c.id = tbd.community_id
    WHERE   c.launched_on_xxx < now()
    GROUP BY    c.id, c.subdomain, c.launched_on_xxx;
    SELECT dblink_disconnect();'
      LANGUAGE SQL;

2 个答案:

答案 0 :(得分:3)

您的功能可能如下所示:

CREATE OR REPLACE FUNCTION test()
  RETURNS TABLE(id int, subdomain varchar, launched_on_xxx timestamp
               ,uvs bigint, pvs bigint) AS
$func$
SELECT dblink_connect('other_DB');

SELECT c.id
      ,c.subdomain
      ,c.launched_on_xxx
      ,COALESCE(SUM(tbd.new_unique_visitors), 0) AS uvs
      ,COALESCE(SUM(tbd.page_views), 0) AS pvs
FROM   dblink('
         SELECT id, subdomain, launched_on_xxx
         FROM   communities
         WHERE  launched_on_xxx < now()')
       AS c(id int, subdomain varchar, launched_on_xxx timestamp)
LEFT   JOIN days_of_center tbd ON tbd.community_id = c.id
GROUP  BY c.id, c.subdomain, c.launched_on_xxx;

SELECT dblink_disconnect();
$func$ LANGUAGE SQL;
  • WHERE子句拉入dblink函数。不开始获取行更有效 - 而不是从外部数据库中提取它们然后丢弃它们。

  • 使用美元引用以避免引用混淆。这已经成为具有更大功能定义的标准程序。

要以“表格式”输出,请调用一个返回多列的函数,如下所示:

SELECT * FROM test();

答案 1 :(得分:2)

最简单的例子就是这个;

CREATE FUNCTION test() RETURNS TABLE(num INT) AS
  'SELECT id FROM table1'
  LANGUAGE SQL;

SELECT * FROM test()

An SQLfiddle to test with

如果你需要一个参数,这是另一个例子;

CREATE FUNCTION test(sel INT) RETURNS TABLE(val VARCHAR) AS
  'SELECT value FROM table1 WHERE id=sel'
  LANGUAGE SQL;

SELECT * FROM test(2)

Another SQLfiddle to test with