如何在具有select语句的pgsql函数中引用timestamp变量

时间:2015-10-12 11:17:27

标签: postgresql sql-timestamp

您好我正在尝试编写一个pgsql函数,该函数将表数据复制到csv文件,并且在使用函数内部的变量值时遇到困难,如下所示:

CREATE OR REPLACE  FUNCTION test3() RETURNS void
    LANGUAGE plpgsql
    AS $$
DECLARE
_currenttime timestamp := now();
BEGIN
copy (SELECT * FROM table1 WHERE createdtime < _currenttime - INTERVAL '1 days') TO '/tmp/table1.csv';
END
$$;

访问该功能时出错:

select test3();
  

错误:列&#34; _currenttime&#34;不存在第1行:... py(SELECT *   FROM table1 WHERE createdtime&lt; _currentti ...                                                                ^ QUERY:copy(SELECT * FROM bpminstance WHERE createdtime&lt; _currenttime -   INTERVAL&#39; 1天&#39;)TO&#39; /tmp/table1.csv'

请求您的帮助。

1 个答案:

答案 0 :(得分:0)

CREATE OR REPLACE  FUNCTION test3() RETURNS void
    LANGUAGE plpgsql
    AS $$
 DECLARE
_currenttime timestamp;
qry text;
BEGIN
_currenttime := NOW() - interval '1 day';
select 'copy (SELECT * FROM table1 WHERE createdtime < '''||_currenttime||''') TO ''/tmp/table1.csv''' into qry;
execute qry;
--codes
END
$$;