无法创建SQL函数-导致错误:“ $$
或附近的不加引号的美元报价字符串这是环境:Greenplum数据库5.20.1
我正在尝试创建一个函数,该函数将以逗号分隔的数据元素的有序集合作为单个文本返回。我试图使用listagg函数,但我发现它不支持使用order,同时还进行了不同的处理。我已经将我想做的事情精简为我认为需要做的事情-这是创建一个SQL函数,该函数在内联查询(已被重复数据删除)上使用listagg函数。到目前为止,一切都很好。我有一段时间没有做任何Postgres代码了,所以我很生锈。我甚至无法正确创建SQL函数。
DROP TABLE IF EXISTS test_table;
CREATE TABLE test_Table
(
abk INTEGER NOT NULL
, effective_date DATE NOT NULL
, end_date DATE NOT NULL
, anattrib CHARACTER (70) NOT NULL
)
WITH (OIDS = FALSE)
DISTRIBUTED RANDOMLY;
INSERT INTO test_table(abk,effective_Date,end_date,anattrib) VALUES(1,'2019-01-01','2019-12-31','A');
INSERT INTO test_table(abk,effective_Date,end_date,anattrib) VALUES(1,'2019-06-01','9999-12-31','A');
INSERT INTO test_table(abk,effective_Date,end_date,anattrib) VALUES(1,'2019-01-01','2019-12-31','B');
INSERT INTO test_table(abk,effective_Date,end_date,anattrib) VALUES(1,'2020-01-01','9999-12-31','C');
COMMIT;
有效且看起来像这样的SQL:
SELECT string_agg(myAlias.anattrib,', ' ORDER BY myAlias.anattrib)
FROM (SELECT DISTINCT anattrib FROM test_table
WHERE abk=1 AND '2019-06-01' BETWEEN effective_Date AND end_Date OR '2019-06-02' BETWEEN effective_Date AND end_Date) myAlias;
在看起来像这样的功能中:
CREATE OR REPLACE FUNCTION test_func(myBK INT, dt1 DATE, dt2 DATE) RETURNING VARCHAR(1000) AS
$$
SELECT string_agg( myAlias.anattrib,', ' ORDER BY myAlias.anattrib) AS anattrib_list
FROM
(SELECT DISTINCT anattrib FROM test_table WHERE abk= $1
AND (($2 BETWEEN EFFECTIVE_DATE AND END_DATE) OR ($3 BETWEEN EFFECTIVE_DATE AND END_DATE))) myAlias;
$$
LANGUAGE SQL;
我什至不能编译SQL函数-它给了我
ERROR: syntax error at or near "CREATE OR";
Error while executing the query. Error 7. SQLSTATE 42601
ERROR: unterminated dollar-quoted string at or near "$$
LANGUAGE SQL";
Error while executing the query. Error 7. SQLSTATE 42601
必须简单一些。但这似乎与SQL函数定义的语法匹配。
答案 0 :(得分:0)
只需更改功能代码中RETURNS的RETURNING子句:
CREATE OR REPLACE FUNCTION test_func(myBK INT, dt1 DATE, dt2 DATE) RETURNS VARCHAR(1000) AS
$$
SELECT string_agg( myAlias.anattrib,', ' ORDER BY myAlias.anattrib) AS anattrib_list
FROM
(SELECT DISTINCT anattrib FROM test_table WHERE abk= $1
AND (($2 BETWEEN EFFECTIVE_DATE AND END_DATE) OR ($3 BETWEEN EFFECTIVE_DATE
AND END_DATE))) myAlias;
$$
LANGUAGE SQL;