在postgres函数中使用now或current_timestamp

尝试使用||更新表中的JSONB列运算符,然后使用now或current_timestamp插入当前时间,但不能。

我的jsonb_column结构是

{
  "status": "oldStatus","statusUpdatedTimestamp": null //this field might be present or not,if it's present it has to be overwritten. if not,it has to be added
}
create or replace function update_jsonb() 
returns trigger language plpgsql 
as $function$ 
begin 
    if (TG_OP = 'UPDATE' and old.jsonb_column ->> 'status' <> new.jsonb_column ->> 'status') then 
        --need statusUpdatedTimestamp to have the current time
        new.jsonb_column = new.jsonb_column || '{"statusUpdatedTimestamp": ' now ' }';
    end if;

    return new;
end;
$function$ ;

我对jsonb_column的预期输出是

{
  "status": "newStatus","statusUpdatedTimestamp": '2019-12-11 10:10:35'
}
lzdfkwdz 回答:在postgres函数中使用now或current_timestamp

使用功能import module ,例如:

jsonb_build_object()

select jsonb_build_object('statusUpdatedTimestamp',now()::text)

                     jsonb_build_object
-------------------------------------------------------------
 {"statusUpdatedTimestamp": "2019-12-11 19:39:22.950725+01"}
(1 row)

触发函数的主体可能如下所示:

select jsonb_build_object('statusUpdatedTimestamp',to_char(now(),'YYYY-MM-DD HH24-MI-SS'))

                jsonb_build_object
---------------------------------------------------
 {"statusUpdatedTimestamp": "2019-12-11 19:39:52"}
(1 row)
本文链接:https://www.f2er.com/2939416.html

大家都在问