天天看點

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)    轉換格式為字元串