将字符串的所有字符替换为星号,除了MSSQL中的第一个字符和空格

时间:2014-03-05 09:13:51

标签: sql-server sql-server-2008 tsql sql-server-2008-r2 sql-server-2012

我很想知道是否可以通过函数在mssql中散列敏感数据,并为所有字段保留第一个字符“as-is”。示例:

“Jon Kirk”这个名字应该被提取为J ** K ***

3 个答案:

答案 0 :(得分:2)

我最初发布了一个递归解决方案。这更快:

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

答案 1 :(得分:0)

这样的事情怎么样?

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

这是最快的解决方案(虽然它根本不是很好):

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) )

答案 2 :(得分:0)

如果您的名字被分开并且中间没有空格,则可以更快地隐藏敏感信息,而无需进行怪异的循环:

DECLARE @t as varchar(20) = 'Billy'

SELECT CONCAT( LEFT(@t, 1), REPLICATE('*', LEN(@t) - 1) )

输出B****