带参数的列postgres函数的默认值 [英] Default value for column postgres function with argument

查看:935
本文介绍了带参数的列postgres函数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个采用一个参数的postgres函数。我想将此函数设置为列的默认值,但是我不确定如何将参数传递到表定义中。

I have a postgres function that takes one argument. I want to make this function the default value for a column, but I'm not sure how to pass the argument into the table definition.

这就是我的意思,我在表中有两列如下所示:

This is what I mean, I have two columns in the table that look like this:

trade_id INTEGER NOT NULL
group_id INTEGER DEFAULT trade_id_f(argument_goes_here);

我想将 DEFAULT 的值设为 group_id trade_id_f(trade_id)的返回值,其中 trade_id 是要插入的记录的 trade_id

I want to make the DEFAULT value of group_id to be the return value of trade_id_f(trade_id) where trade_id is the trade_id of the record to be inserted.

postgres函数对我来说是陌生的,

I'm new to all things postgres functions, is this possible?

推荐答案

不幸的是,您不能这样做,因为(对于文档):

Unfortunately, you cannot do that, because of (for the documentation):


该值是任何无变量表达式(不允许子查询和
对当前表中其他列的交叉引用)。

The value is any variable-free expression (subqueries and cross-references to other columns in the current table are not allowed).

您可以使用触发器,例如:

You can use a trigger, e.g.:

create table the_table (
    trade_id int not null,
    group_id int);

create or replace function trade_id_trigger ()
returns trigger language plpgsql as $$
begin
    new.group_id:= new.trade_id+ 1;
    return new;
end $$;

create trigger trade_id_trigger
before insert or update on the_table
for each row execute procedure trade_id_trigger();

insert into the_table values (1,1);

select * from the_table;

 trade_id | group_id
----------+----------
        1 |        2
(1 row)

这篇关于带参数的列postgres函数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆