Published on

April 19, 2015

Writing Scripts to Remove Special Characters in SQL Server

When it comes to interviewing candidates for a SQL Server position, there are certain questions that may not be the best indicators of their skills. One such question is how to write a script that removes all special characters and parses alpha-numeric values only. While this question may seem straightforward, it actually requires experience in writing scripts and trial and error to get it right.

It’s important to note that this question is subjective and may not accurately assess a candidate’s abilities. However, some interviewers may consider it a crucial test. In my opinion, there are better questions that can be asked to evaluate a candidate’s SQL Server skills.

That being said, if you’re interested in writing a script to remove special characters and parse alpha-numeric values only, here’s an example of how it can be done:

CREATE FUNCTION dbo.UDF_ParseAlphaChars (@string VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
    DECLARE @IncorrectCharLoc SMALLINT
    SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)
    
    WHILE @IncorrectCharLoc > 0
    BEGIN
        SET @string = STUFF(@string, @IncorrectCharLoc, 1, '')
        SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)
    END
    
    RETURN @string
END
GO

-- Test
SELECT dbo.UDF_ParseAlphaChars('AB"_I+{D[]}4|:e;"5,<.F>/?6')
GO

The above script defines a user-defined function called dbo.UDF_ParseAlphaChars that takes a string as input and returns the same string with all special characters removed, leaving only alpha-numeric values. The function uses the PATINDEX function to find the position of the first occurrence of a special character in the string, and the STUFF function to remove that character. This process is repeated until no more special characters are found.

You can test the function with the provided example by executing the following query:

-- Test
SELECT dbo.UDF_ParseAlphaChars('AB"_I+{D[]}4|:e;"5,<.F>/?6')
GO

The result of the above query will be: ABCID4e5F6, which is the input string with all special characters removed.

If you’re interested in learning more about this function and reading additional comments, you can refer to my earlier blog post on Function to Parse AlphaNumeric Characters from String.

Remember, while writing scripts to remove special characters and parse alpha-numeric values can be a useful skill in SQL Server, it’s important to consider the overall abilities and experience of a candidate when evaluating their suitability for a position.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.