Skip to main content

TSQL Remove Special Characters

By June 14, 2019Code, SQL

Usage: Select dbo.StripSpecialChars(‘abc12+=\34def’); returns abc1234def

Create Function [dbo].[StripSpecialChars](@Temp VarChar(1000))
Returns VarChar(1000)

    Declare @KeepValues as varchar(50)
    Set @KeepValues = '%[^a-zA-Z0-9 ]%'
    While PatIndex(@KeepValues, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')

    Return @Temp

Adjust the @KeepValues as needed. Or if you want to get fancy, add it as a second input variable.

Derrick Emery

Derrick has more than ten years background in web development.In his free time Derrick is an enthusiast of furthering his knowledge, loves taking bike rides through the woods, playing computer games with friends and cooking.

Leave a Reply