Search code examples
sqlsql-serverstringnvarchar

SQL: insert space before numbers in string


I have a nvarchar field in my table, which contains all sorts of strings. In case there are strings which contain a number following a non-number sign, I want to insert a space before that number.

That is - if a certain entry in that field is abc123, it should be turned into abc 123, or ab12.34 should become ab 12. 34.I want this to be done throughout the entire table.

What's the best way to achieve it?


Solution

  • You can try something like that:

    select left(col,PATINDEX('%[0-9]%',col)-1 )+space(1)+
           case
             when PATINDEX('%[.]%',col)<>0 
               then substring(col,PATINDEX('%[0-9]%',col),len(col)+1-PATINDEX('%[.]%',col))
                    +space(1)+
                    substring(col,PATINDEX('%[.]%',col)+1,len(col)+1-PATINDEX('%[.]%',col))
             else substring(col,PATINDEX('%[0-9]%',col),len(col)+1-PATINDEX('%[0-9]%',col))
           end       
    from tab
    

    It's not simply, but I hope it will help you.

    SQL Fiddle

    I used functions (link to MSDN): LEFT, PATINDEX, SPACE, SUBSTRING, LEN and regular expression.