2

Is there any SQL statements to replace everything in a string with an 'X'. The strings aren't all the same length so it makes it a bit tricky. I haven't been able to find anything that does this except the function below but it takes a long time when I pass in 'a-z0-9' since I have to search on all of those but I really just want to replace everything no matter what it is.

[dbo].[cfn_StripCharacters]
 (
    @String NVARCHAR(MAX), 
 @MatchExpression VARCHAR(255)='a-z0-9'
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
SET @MatchExpression =  '%['+@MatchExpression+']%'

WHILE PatIndex(@MatchExpression, @String) > 0
    SET @String = Stuff(@String, PatIndex(@MatchExpression, @String), 1, 'X')

RETURN @String

For example the data column looks like this and I want to replace the whole string with x's:

975g -> XXXX

ryth5 -> XXXXX

1234vvsdf5 -> XXXXXXXXXX

test1234 -> XXXXXXXX

2
  • possible duplicate of Regex pattern inside SQL Replace function? Commented Aug 19, 2014 at 16:44
  • If your goal is to obfuscate a field, why do you care the length of the string? Can you just update tableName set protectedInfoColumn = 'XXX';? Commented Aug 19, 2014 at 16:51

3 Answers 3

8

If this is SQL Server, you can use the REPLICATE function and simply replicate x the LEN() of the string.

SELECT REPLICATE('x', LEN(@String))

sqlFiddle

Edit - Looks like this is also available in MySQL via REPEAT() but I haven't tested

Sign up to request clarification or add additional context in comments.

2 Comments

This works perfectly. Have never heard of the Replicate function. Thank you!
Hi @Tom - what is the way if I need to replace all characters except spaces ?
0

You can use Replicate and Len functions to replace all characters.

declare @str varchar(20)

set @str = 'abc'

select @str = REPLICATE('X', len(@str))

select @str

1 Comment

Thanks. Had to give the 'check' to the one who answered it first.
-1

There are no built in functions to do it. You can write a CLR function that does a regex replace, though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.