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