where 子句中的 PostgreSQL 函数

And*_*rov 1 postgresql functions

我有这样的表:

table a (
   id 
   --
   p1 text,
   p2 text,
   p3 text
)
Run Code Online (Sandbox Code Playgroud)

当我编写一些使用该表的函数时,我需要编写这样的代码

create or replace function ...

select * from a
   where a.p1 is not null
     and a.p2 is not null
     and a.p3 is not null
Run Code Online (Sandbox Code Playgroud)

我想创建一个函数,

 create function my_function(??? val) returns boolean as -- what I need to place instead of ???
 $$
 begin
     return val.p1 is not null 
        and val.p2 is not null
        and val.p3 is not null;
 end;
 $$ language plpgsql
Run Code Online (Sandbox Code Playgroud)

其中我将传递当前行的“this”实例(我不知道它是如何调用的),我的函数将如下所示:

select * from a
   where my_function(???) -- what I need to place instead of ???
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 我可以创建my_function像上面这样的函数吗?

  2. 如果第1点为真,我需要为参数编写什么类型?我需要在条款上写什么where

小智 5

对于创建的每个表,都会创建一个具有相同名称的类型。因此,您可以定义函数来接受表的类型。

这样的函数也最好写成 SQL 函数,以避免 PL/pgSQL 的开销。

create function my_function(val a) returns boolean as 
 $$
 select val.p1 is not null 
    and val.p2 is not null
    and val.p3 is not null;
 $$ 
 language sql
 stable;
Run Code Online (Sandbox Code Playgroud)

ina(val a)您的表的名称。

您可以通过以下方式使用该功能:

select * 
from a
where my_function(a);
Run Code Online (Sandbox Code Playgroud)