在數據庫中難免會遇到需要對數據進行脫敏的操作,無論是姓名,還是身份證號。
最近遇到一個需求,需要對姓名進行脫敏:
- 姓名長度為2,替換為姓+*;
- 姓名長度為3,替換中間字符為*;
- 姓名長度為4,替換第3個字符為*;
經過一番搜索之后,最終找到了3種方式的實現,具體如下。
一、先查找,再替換
select replace('陳宏宏',substr('陳宏宏',2,1),'*') as name from dual;
注意:此種方法通過對第2個字符進行替換,如果名字為疊名,則會發生上述誤替換情況;
二、拼接
select substr('陳宏宏',1,1)||'*'||substr('陳宏宏',3,1) as name from dual;
三、使用regexp_replace進行精准替換
select regexp_replace('陳宏宏','(.)','*',2,1) as name from dual;
注意:regexp_replace支持使用正則表達式對字符串進行替換,該語句解釋為從第2個字符開始,取任意1個字符,替換為*;
四、完整的替換代碼
create table temp_cwh_002 as
select a.acc_nbr, a.act_city, a.city_name,a.number1, a.number2, case when length(a.cust_name) = 2 then regexp_replace(cust_name,'(.)','*',2,1) when length(a.cust_name) = 3 then regexp_replace(cust_name,'(.)','*',2,1) when length(a.cust_name) = 4 then regexp_replace(cust_name,'(.)','*',3,1) else cust_name end cust_name, a.acc_nbr2, a.param_value from temp_cwh_001 a where length(a.cust_name) <= 4
END 2019-01-02 16:44:13