4

I have a sample text that contains '-' or ' '. So I want a sql replace statement that replaces both '-' and ' ' with ''.

My query is:

SELECT REPLACE('SQL-Tu torial','-',' ','');

Desired outcome:

SQLTutorial

Error: I get error for Replace function arguments.

The replace function requires 3 argument(s).

Any help?

1
  • 1
    The documentation clearly states that replace method accepts 3 parameters, not 4.... Commented Oct 9, 2018 at 15:44

4 Answers 4

9

You can't use 3 parameters in a REPLACE function. Instead you can use it twice just like below :

SELECT REPLACE(REPLACE('SQL-Tu torial', '-', ''), ' ', '');

Output :

SQLTutorial
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this helped me!
6

Nest two REPLACE functions.

REPLACE(REPLACE())

Comments

5

You can also define a table with all the characters you want to replace and then use a single replace statement while selecting from the table:

declare @charToReplace table (char_to_replace varchar(1))
declare @tempString varchar(max) = 'SQL-Tu torial'

insert into @charToReplace values ('-'), (' ')

select @tempString = replace(@tempString, char_to_replace, '') 
from @charToReplace

select @tempString as result

Result:

enter image description here

1 Comment

That is very cool. I didn't know Replace() would do that.
1

If you have more than two characters to be replaced, you can use TRANSLATE that came in 2017. Below example replaces "-", " " and "@" with "#" using TRANSLATE and then replaces "#" with "" using REPLACE. I.e., replace "-", " ", "@" and "#" with "". TRANSLATE doesn't buy you anything if you only want to substitute two characters, though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.