MSSQL - 基于映射表屏蔽数据

时间:2017-04-18 11:22:22

标签: sql sql-server tsql replace masking

希望使用MSSQL 2008R2按照以下映射执行数据屏蔽:

映射表

A = C
B = A
C = E
1 = 3
2 = 1
3 = 9

原始

ABC123

屏蔽

CAE319

这个想法是使用替换,但第二个替换函数将替换先前替换的值。

select Replace(Replace(Replace(Replace(Replace(REPLACE('ABC123', 'A', 'C'), 'B', 'A'), 'C', 'E'), '1', '3'), '2', '1'), '3', '9')

结果: CAE319

P.S。编辑的值,因为在这种情况下不能使用反向或反向替换

任何想法?

2 个答案:

答案 0 :(得分:3)

如果你想要更多的表格方法。

下面有两个代码段,它们将掩盖或取消一个字符串。轻松转换为UDF甚至放在CROSS APPLY

Declare @Mask table (MapFrom varchar(10),MapTo varchar(10))
Insert into @Mask values 
('A','C'),
('B','D'),
('C','E'),
('1','2'),
('2','3'),
('3','9')


Declare @Yourtable table (ID int,SomeCol varchar(max))
Insert Into @Yourtable values
(1,'ABC123')

-- To Mask
Declare @U varchar(max) ='ABC123'

Select NewSting = Stuff((Select ''+S 
    From (
        Select N
                ,S=IsNull(MapTo,Substring(@U,N,1))
            From (Select Top (Len(@U)) N=Row_Number() Over (Order By (Select null)) From master..spt_values)  N
            Left Join @Mask on Substring(@U,N,1)=MapFrom
        ) X 
    Order By N
    For XML Path ('')),1,0,'') 

-- To UnMask
Declare @M varchar(max) = 'CDE239'

Select NewSting = Stuff((Select ''+S 
    From (
        Select N
                ,S=IsNull(MapFrom,Substring(@M,N,1))
            From (Select Top (Len(@M)) N=Row_Number() Over (Order By (Select null)) From master..spt_values)  N
            Left Join @Mask on Substring(@M,N,1)=MapTo
        ) X 
    Order By N
    For XML Path ('')),1,0,'') 

答案 1 :(得分:1)

只需更改替换顺序并反转结果

即可
select REVERSE( Replace(Replace(Replace(Replace(Replace(REPLACE('321CBA', '3', '9'), '2', '3'), '1', '2'), 'C', 'E'), 'B', 'D'), 'A', 'C'))

结果:

CDE239

编辑:

Declare @Mask table (MapFrom varchar(10),MapTo varchar(10))
Insert into @Mask values 
('A','C'),
('B','A'),
('C','E'),
('1','3'),
('2','1'),
('3','9')

DECLARE @pos INT
    ,@result VARCHAR(100)
    ,@maskfrom NCHAR(1)
    ,@mask_to NCHAR(1);

SET @result = 'ABC123';
SET @pos = 1

WHILE @pos < LEN(@result) + 1
BEGIN
    SELECT @mask_to = MapTo
    FROM @mask
    WHERE MapFrom = substring(@result, @pos, 1)

    SET @result = STUFF(@result, @pos, 1, @mask_to);
    SET @pos = @pos + 1;
END

SELECT @result

<强> RESULT

CAE319