Skip to content
Home » SQL Exercise – 8

SQL Exercise – 8

SQL Exercise:

Create a SQL function that takes a string as input and removes all special characters (keeping only alphanumeric characters and spaces).

The following is a list of special characters that need to be removed from the string:

@!#$%*()^-_=+{}[]|\/:;”””&<>./,?




Solution:

CREATE FUNCTION dbo.RemoveSpecialCharacters (@InputString NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
-- List of characters to remove
DECLARE @SpecialChars NVARCHAR(100) = '@!#$%*()^-_=+{}[]|\/:;""''&<>./,?';
-- Replacement characters (empty spaces matching length of @SpecialChars)
DECLARE @ReplacementChars NVARCHAR(100) = REPLICATE(' ', LEN(@SpecialChars));

-- Use TRANSLATE to replace special characters with spaces, then remove spaces using REPLACE
RETURN REPLACE(TRANSLATE(@InputString, @SpecialChars, @ReplacementChars), ' ', '');
END;

Let’s test the function.

DECLARE @InputString NVARCHAR(MAX) = 'ABCDE%12&#$()45BCF!@';
SELECT dbo.RemoveSpecialCharacters(@InputString) AS OutputString;

Output:

 

Explanation:

  1. @SpecialChars:
    • Contains the list of special characters you want to remove.
  2. @ReplacementChars:
    • Replaces each special character with a space. The REPLICATE function creates a string of spaces equal to the length of @SpecialChars.
  3. TRANSLATE:
    • TRANSLATE Maps each character in @SpecialChars to the corresponding character in @ReplacementChars (spaces).
  4. REPLACE:
    • Removes the spaces introduced by the TRANSLATE function.

 

Loading

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from SQL BI Tutorials

Subscribe now to keep reading and get access to the full archive.

Continue reading