2

I have a string which is in 99999 124 fdsg format.

I want to replace the first space with - and the next space with a non-space. My expected result will look like this:

99999-124fdsg 

To replace the first char I used this expression:

stuff(Product,charindex('',product),1,'-')as trim 

Because I want to name the new column as trim. How can I do for the second character?

1
  • Didn't you just ask this question? Commented Nov 29, 2016 at 17:08

2 Answers 2

4

Charindex has last parameter start_location use it to search for second empty string

Try this

DECLARE @str VARCHAR(50) = '99999 124 fdsg'

SELECT Stuff(Stuff(@str,Charindex(' ',@str),1,'-'),Charindex(' ',@str,Charindex(' ',@str) + 1),1,'') 

Result : 99999-124fdsg

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

2 Comments

I think, there's no need to search for the second blank, because the second blank is the only one after the first operation...
@Shnugo OP mentioned the next space with a non-space. So it may not be the last empty string. If it is last empty string then definitely your answer looks lot better
3

Assuming, that you example with STUFF works correctly for the first blank you can just wrap this with REPLACE. After STUFF there's only the other blank left:

replace(stuff(Product,charindex(' ',product),1,'-'),' ','')

Working example:

DECLARE @s VARCHAR(50) = '99999 124 fdsg';
select replace(stuff(@s,charindex(' ',@s),1,'-'),' ','')

The result

99999-124fdsg

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.