【问题标题】:create function error to return any in PostgreSQL创建函数错误以在 PostgreSQL 中返回任何错误
【发布时间】:2019-09-14 16:04:12
【问题描述】:

我正在尝试创建一个函数以在我的 PostgreSQL 中为将来返回一行或多行, 对于这种情况,我使用 DBeaver 创建一个函数 当我在 DBeaver 中创建一个新函数时,容器基于 public, 我的功能是这样的:

CREATE OR REPLACE FUNCTION public.test()
returns any AS $fortest$
declare
    fortest any;
BEGIN
    select * from into fortest from people where email = "test@email.com"
    return fortest;
END;
$fortest$ LANGUAGE plpgsql;

当我保存它时,我得到了这样的错误

ERROR: syntax error at or near "any"
  Position: 50

我写错了语法吗?

【问题讨论】:

标签: sql postgresql sql-function dbeaver


【解决方案1】:

您似乎正在寻找Postgres Set Returning Function。这应该与您想要的非常接近:

create function test() 
     returns setof people 
     as 'select * from people where email = ''test@email.com'' ;' 
language sql;

Demo on DB Fiddle

给定上述函数和以下数据:

| id  | email            | name |
| --- | ---------------- | ---- |
| 1   | test@email.com   | foo  |
| 2   | test@email.com   | bar  |
| 3   | notest@email.com | baz  |

这个查询:

SELECT * from test();

返回:

| id  | email          | name |
| --- | -------------- | ---- |
| 1   | test@email.com | foo  |
| 2   | test@email.com | bar  |

另一个(可能更明智)的选择是使用以下函数:

create function test() 
     returns setof people 
     as 'select * from people;' 
language sql;

以下查询返回与上图相同的结果:

SELECT * from test() where email = 'test@email.com';

Demo on DB Fiddle

【讨论】:

  • 在加入表格时,我也返回setof people,但它不起作用
猜你喜欢
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 2019-08-30
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多