Search code examples
sqlsql-serversql-server-2014

SQL remove characters from string and leave number only


I have string(nvarchar) from db data and I would like to transfer it to numbers only. I was searching on Google for solution but I didnt find anything. I found something similiar here on StackOverflow but everything was removing characters only from left side, but if there is any character on right side or between numbers it wont work.

Solution I found but is not working:

select substring(XX, 
       PatIndex('%[0-9]%', XX), 
       len(XX))

For example I have text: '4710000 text' so this substring returns me same text I putted inside of it which is again '4710000 text'. Is there any other way how to do that? Without creating functions or using IFs, begins, variables (@text etc.).


Solution

  • Try this, it seems to work like a charm. I wish I could take credit but it's from this post. If it works for you please give him the upvote.

    The 'with' is just a CTE that sets up test data.

    with tbl(str) as (
      select '4710000 text'
    )
    SELECT
        (SELECT CAST(CAST((
            SELECT SUBSTRING(str, Number, 1)
            FROM master..spt_values
            WHERE Type='p' AND Number <= LEN(str) AND
                SUBSTRING(str, Number, 1) LIKE '[0-9]' FOR XML Path(''))
        AS xml) AS varchar(MAX)))
    FROM
        tbl