Replace all characters of string to asterisks exce

2019-07-17 15:51发布

问题:

I`m was wonder if it is possible to hash sensitive data in mssql via function and to leave first character “as-is” for all the fields. Example:

"Jon Kirk” name should be extracted as J** K***

回答1:

I had posted a recursive solution at first. This is faster:

declare @name varchar(20) = 'Jon Kirk'

declare @loop int = len(@name)

while @loop > 1
select @name = stuff(@name, @loop, 1, 
case when substring(@name, @loop-1,2) like '% ' then ' '
     when substring(@name, @loop-1,2) like ' %' then substring(@name, @loop,1)
else '*' end), @loop+=-1

select @name


回答2:

How about something like this?

declare @s varchar(50) = 'Jon kirk'

;with cte as (
    select 1 as i, cast (' ' + ltrim (@s) as varchar(50)) as s
    union all
    select i + 1
        , cast (
            case when substring (s, i, 2) like '% %'
            then s
            else stuff (s, i + 1, 1, '*') end
        as varchar(50))
    from cte
    where i < len (s)
)

select top 1 ltrim (s) as s
from cte
order by i desc

Here is the fastest solution (although it is not pretty at all):

declare @s varchar(50) = 'Jon kirk'

select left (
      left (@s, 1)
    + case when substring (@s, 1, 2) like '% %' then substring (@s, 2, 1) else '*' end
    + case when substring (@s, 2, 2) like '% %' then substring (@s, 3, 1) else '*' end
    + ...
    + case when substring (@s, 48, 2) like '% %' then substring (@s, 49, 1) else '*' end
    + case when substring (@s, 49, 2) like '% %' then substring (@s, 50, 1) else '*' end
    , len (@s) )