Search code examples
sql-serversql-server-2016sql-server-2017

Remove characters from text using TRANSLATE function (replace them with empty strings)


Let's say I have a string:

DECLARE @text VARCHAR(20) = 'abr_akad-ab#ra';

and I want to remove all _-# characters from the text.

Normally I would user REPLACE function to that, something like:

SELECT REPLACE(REPLACE(REPLACE(@text, '-', ''), '_', ''),'#','')

Can I do that with single TRANSLATE statement somehow?


Solution

  • You can try the following query:

    DECLARE @text AS VARCHAR(20) = 'abr_akad-ab#ra';
    SELECT REPLACE(TRANSLATE(@text, '_-#', '###'), '#', '')
    

    it will return the output as abrakadabra

    Working demo on db<>fiddle