Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

SQL Server: Query to remove special characters from string

$
0
0

The following query can be used to remove special characters from a string using the STUFF function:

DECLARE @String VARCHAR(100)='Hello@!#$%^&*()_+ World'

SELECTSTUFF(@String,PATINDEX('%[^a-zA-Z0-9 ]%', @String), 1,'')AS [CleanString]

WHILEPATINDEX('%[^a-zA-Z0-9 ]%', @String)> 0

BEGIN

  SET @String =STUFF(@String,PATINDEX('%[^a-zA-Z0-9 ]%', @String), 1,'')

END

SELECT @String AS [CleanString]

This query uses the PATINDEX function to search for any characters that are not letters, numbers, or spaces. The STUFF function then replaces these characters with an empty string. The process is repeated until all special characters are removed. The final result is stored in the @String variable.


Viewing all articles
Browse latest Browse all 265

Trending Articles