postgresql update 设置某列为某些条件生成的值

with tmp as( select row_number() over() as rownum,id idd  from bas_cm_verification_strategy)
update bas_cm_verification_strategy
set code = COALESCE(to_char(create_time, 'yyyyMMdd')) || lpad(CAST(tmp.rownum as VARCHAR), 3, '0')
from tmp where id = tmp.idd;

需求说明:

   接到一个需求:给表bas_cm_verification_strategy新增一个code字段,表中历史数据要根据创建时间+001递增来设置code的值。

注释:

其中 row_number() over() 获取到的是数据的行号,此处为了省事没有用序列。

lpad(string text, length int [, fill text])    通过填充字符 fill (缺省时为空白), 把 string 填充为长度 length。 如果 string 已经比 length 长则将其截断(在右边)。类似的还有rpad,不过填充的位置相反。

COALESCE(to_char(create_time, 'yyyyMMdd')) 格式化时间

CAST(tmp.rownum as VARCHAR)    转换格式为字符串

你可能感兴趣的:(数据库)