PostgreSQL:获取输入参数作为行值

标签 postgresql syntax plpgsql

我创建了一个简单的函数:

create function my fucnction(uuid, uuid, date) returns boolean as
$$
    select ... from t where t.f1 = $1 and t.f2 = $2 and t.f3 = $3;
$$
language sql stable;

如果我可以将输入参数作为单行访问(在我的函数中等于 ($1, $2, $3)),那么在语法方面会很棒,所以我可以这样写:

create function my fucnction(uuid, uuid, date) returns boolean as
$$
    select ... from t where (t.f1, t.f2, t.f3) = <the input parameters row>;
$$
language sql stable;

等于:

create function my fucnction(uuid, uuid, date) returns boolean as
$$
    select ... from t where (t.f1, t.f2, t.f3) = ($1, $2, $3);
$$
language sql stable;

这可能吗?

最佳答案

这对我有用。我是row()的忠实粉丝函数,尤其是在 count(distinct row()) 查询中。

create OR REPLACE function my_function(text,text,text) returns bigint as
$$
    select count(*) from t where row(t1,t2,t3) = row($1,$2,$3);
$$
language sql stable;

select * from my_function('a','b','c');

注意:这似乎也适用于您的 (t1,t2,t3) 语法。

编辑:我可能误解了您的问题。如果你特别想要像触发器中那样的命名引用,你总是可以传入一个记录类型(这里我使用的是表 t 定义的类型)。可能值得研究 record datatype以及 PLPGSQL 如果您需要更复杂的函数:

create OR REPLACE function my_function(blast t) returns bigint as
$$

    select count(*) from t where (t1,t2,t3) = blast;
$$
language sql stable;

select * from my_function(row('a','b','c'));

最后一个alternative - 没有给出上面语法的好处,大概是因为类型没有定义,但是如果你需要在输入上单独的参数:

create OR REPLACE function my_function(_1 text, _2 text, _3 text) returns bigint as
$$

    select count(*) from t where (t1,t2,t3) = (my_function._1, my_function._2, my_function._3);
$$
language sql stable;

select * from my_function('a','b','c')

关于PostgreSQL:获取输入参数作为行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44966260/

相关文章:

mysql - 在 postgresql 中实现 UML 类 : create type vs create table

django - 强制对 Django 模型进行级联删除

postgresql - 如何在 PostgreSQL 中将 timestamp(0) 设置为默认值而不是 timestamp(6)?

sql - PostgreSQL "IF"语法错误

arrays - 选择整数数组数组的每个第一个元素进行数组

php - 用于 Postgresql 查询的 PHP 中列名的绑定(bind)变量

C++ 变量声明语法

google-chrome - Chrome 开发者控制台无法运行 JS 循环

postgresql - PostgreSQL 函数中是否有命名参数的约定

arrays - 如何在 PostgreSQL 函数中声明一个行类型数组?