sam sam - 5 months ago 40
SQL Question

Replace string SQL

I have a string which is in

99999 124 fdsg

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


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?


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