1

我开始在 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;
4

2 回答 2

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();
于 2013-05-23T21:27:44.050 回答
2

最简单的例子就是这个;

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

SELECT * FROM test()

一个用于测试的 SQLfiddle

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

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

SELECT * FROM test(2)

另一个用于测试的 SQLfiddle

于 2013-05-23T20:11:04.427 回答