SQL Server: Query to remove special characters from string


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

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

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

WHILE PATINDEX('%[^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.

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

How to drop a PostgreSQL database if there are active connections to it?

In PostgreSQL, you cannot drop a database if there are active connections to it. You must first terminate all connections to the database be...