用于更改列的值(var char(20))的SQL

时间:2013-09-17 06:21:30

标签: postgresql postgresql-9.1

Table_neme:员工详细信息

--------------------------------------------
c_bp_id | value | name  |address
--------------------------------------------
10001   |001    |john   |
10002   |mathew |mathew |
10003   |002    |Ann    |
10004   |003    |isabel |
10005   |maria  |maria  |
10006   |Adam   |Adam   |

我想将更改列'值'更改为

--------------------------------------------
c_bp_id | value | name  |address
--------------------------------------------
10001   |001    |john   |
10002   |**005**|mathew |
10003   |002    |Ann    |
10004   |003    |isabel |
10005   |**006**|maria  |
10006   |**007**|Adam   |
请帮助我吗?

1 个答案:

答案 0 :(得分:1)

好吧,它可能是这样的:

with cte as (
    -- create row_numbers for all values where value is text
    select
        c_bp_id,
        row_number() over(order by c_bp_id) as rn
    from Table1
    where value !~ E'^\\d+$'
)
-- updated
update Table1 as t set
    value = lpad((rn + 1 + (select coalesce(max(value::int), 0) from Table1 where value ~ E'^\\d+$'))::text, 3, '0')
from cte as c
where c.c_bp_id = t.c_bp_id;

<强> sql fiddle demo

这是一个奇怪的查询,我不建议将其投入生产,但如果是一次更新,您可以使用它。我也不知道你为什么跳过004值并开始从005开始计算。