我想将表的值从一种状态更改为另一种类型'A’
,并希望在10分钟后使用python将其变成'B'
postgres。
答案 0 :(得分:0)
欢迎来到SO。请查看帮助指南以[询问]。使用该模板作为问题的模板通常会给您带来获得满意答案的更好机会。 但是,在这种情况下,尽管有很大的遗漏,但我仍然可以看到您的情况:状态达到“ Z”并且需要更新时会发生什么?以后再说。 您的请求包含2个组件,实际上是要运行一个进程以及该状态的滚动更新过程(脚本)。那么Postgres在启动脚本方面没有本地功能。您将必须设置一个cron作业,或者一个条目就是您所拥有的作业计划程序。除了未定义的“ Z”状态问题之外,更新过程并不那么困难。 (因此,发生这种情况时,我将重复AZ来延长代码长度(类似于excel名称列)。基本更新需要简单地将1添加到当前值。但是当然,语句“'A'+ 1 ”不起作用,但是可以使用CHR and ASCII函数获得结果。Chr(ascii('A')+ 1))有效地完成了此操作,因此您可以通过
完成更新Update table_name set status = chr(ascii(status)+1);
但是,一旦状态达到“ Z”,该操作就会失败。嗯,它不会因为产生错误而失败,但是会产生“ [”。在上述情况下,以下脚本会生成“ AA”,并且每次状态达到“ ... Z”时,下一个状态就会变为“ ... AA”。
--- setup
drop table if exists current_stat;
create table current_stat(id serial,status text,constraint status_alpha_ck check( status ~ '^[A-Z]+'));
insert into current_stat(status) values (null), ('A'), ('B'), ('Y'), ('Z'), ('AA'), ('ABZ')
--- Update SQL
with curr_stat as
( select id, status
, chr(ascii(substring(status,char_length(status),1))+1) nstat
, char_length(status) lstat from current_stat)
update current_stat cs
set status = ( select case when status is null or lstat < 1 then 'A'
when substring(status,lstat,1) = 'Z' then overlay( status placing 'AA' from lstat for 2)
else overlay( status placing nstat from lstat for 1)
end
from curr_stat
where cs.id = curr_stat.id
);
select * from current_stat;