需求:更新用户表的工号,格式为“GD1,GD2,...”的格式,如果有数据取最大值再递增
E1:先查询出是否有数据,有数据取最大值再递增,使用nvl函数
/* 查询max值*/
select nvl(max(to_number(replace(t.user_num, 'GD', ''))), 0)
from t_user t
where t.user_num like 'GD%';
E2:创建Oracle序列,start with改为max值
/* Create sequence,start with改为max值 */
create sequence user_num_t_user
minvalue 1
maxvalue 999999999999999999999999999
start with 200
increment by 1
cache 20;
commit;
/* drop sequence */
drop sequence user_num_t_user;
E3:批量更新
/* batch update*/
update t_user
set user_num = 'GD' || user_num_t_user.nextval
where user_num is null
and IS_OUTNET_REG = 0;
E4:如果下次使用序列,记得更改start with的值,因为每次使用都会更新这个值的
上面方法是使用Oracle序列的方法,如果用Oracle的rownum,也是可以实现需求的,脚本如:
update t_user
set user_num = 'GD' ||
(rownum +
(select nvl(max(to_number(replace(t.user_num, 'GD', ''))),
0)
from base_user t
where t.user_num like 'GD%'))
where user_num is null;