PostgreSQL函数执行查询

时间:2015-06-20 05:06:40

标签: sql postgresql plpgsql postgresql-9.3

如果满足条件,我想运行SQL查询,但是我收到以下错误:

错误:单独的$链未完成«$ func $

我的SQL查询是:

CREATE OR REPLACE FUNCTION myfunc()
RETURNS TABLE(dateticket date, timeticket time, userid integer, my_all bigint) AS
    $func$
    BEGIN
            IF (SELECT COUNT(DISTINCT(dateticket)) from tickets) = 1 THEN
               RETURN QUERY EXECUTE 'select t.*
               from (select distinct on (userid) dateticket, timeticket, userid,
               count(*) over (partition by userid) as my_all
               from tickets t
               order by userid, dateticket, timeticket) t
               order by my_all, dateticket, timeticket';
            ELSE
               RETURN QUERY EXECUTE 'select t.*
               from (select distinct on (userid) dateticket, timeticket, userid,
               count(*) over (partition by userid) as my_all
               from tickets t
               order by userid, dateticket, timeticket) t
               order by my_all DESC, dateticket DESC, timeticket DESC';
            END IF;
    END;
    $$ LANGUAGE plpgsql;

2 个答案:

答案 0 :(得分:1)

错误实际上与函数本身的条件或任何内容无关,而是函数创建的语法。您使用$func$启动功能定义,并以$$结束。这不起作用。

$func$更改为$$以修复语法。

答案 1 :(得分:0)

你在函数中有两个错误,一个已经回答另一个错误, RETURN 表的列与函数中使用的选择查询的列名相同,这将导致

  

错误:列引用“dateticket”不明确第1行:(选择   来自门票的COUNT(DISTINCT(dateticket))= 1                                                      ^ DETAIL:它可以指PL / pgSQL变量或表列。 QUERY :(选择   来自票证的COUNT(DISTINCT(dateticket))= 1语境:PL / pgSQL   在IF处函数myfunc()第3行   **********错误**********

因此您需要修改您的功能,如下所示

CREATE OR REPLACE FUNCTION myfunc()
RETURNS TABLE(datet_icket date, time_ticket time, user_id integer, myall bigint) AS
    $$
 BEGIN
     IF (SELECT COUNT(DISTINCT(dateticket)) from tickets) = 1 THEN
         RETURN QUERY EXECUTE 'select t.*
         from (select distinct on (userid) dateticket, timeticket, userid,
         count(*) over (partition by userid) as my_all
         from tickets t
         order by userid, dateticket, timeticket) t
         order by my_all, dateticket, timeticket';
     ELSE
          RETURN QUERY EXECUTE 'select t.*
          from (select distinct on (userid) dateticket, timeticket, userid,
          count(*) over (partition by userid) as my_all
          from tickets t
          order by userid, dateticket, timeticket) t
          order by my_all DESC, dateticket DESC, timeticket DESC';
          END IF;
    END;
    $$ LANGUAGE plpgsql;