Search code examples
sqlsql-serverpatindex

SQL - Get numbers from string after a pound (#) sign


I am attempting to get numbers from a string in SQL Server 2012 that are located after a pound (#) sign and before any spaces that follow. For instance, store numbers. Let's say we have the following:

Big Box Store #450
Big Box Store #768
Little Shop #2
Widgets Warehouse #678
Little Shop #5
Widgets Warehouse #559
Corner Boutiques #32 *CLOSED
Corner Boutiques #67 *CLOSED
Corner Boutiques #12
Buy More #1047 SUPERSTORE
1 Stop Shop #3
1 Stop Shop #17
You 2 Me #16

I would return the following: 450, 768, 2, 678, 5, 559, 32, 67, 12, 1047, 3, 17, 16.

As you can see, not all of the strings have numbers at the very end. Some of them even have a numerical character in the name of the store. I figure the best way of going about this is just to extract the numbers following the pound sign.

Is there a way to do this? I've looked at the following articles:

Query to get only numbers from a string

https://www.sqlservercentral.com/Forums/Topic456023-338-1.aspx

It seems like PATINDEX may be good to use, but I am unsure as what I've tried thus far doesn't return expected results.

Many thanks!


Solution

  • Another similar way... using test data from Tyron. This works even if there isn't a space after the digits.

    DECLARE @t TABLE(
      MyString NVARCHAR(1000)
    );
    
    INSERT INTO @t VALUES 
     ('Big Box Store #450')
    ,('Big Box Store #768')
    ,('Little Shop #2')
    ,('Widgets Warehouse #678')
    ,('Little Shop #5')
    ,('Widgets Warehouse #559')
    ,('Corner Boutiques #32*CLOSED')    --notice no space here
    ,('Corner Boutiques #67 *CLOSED')
    ,('Corner Boutiques #12')
    ,('Buy More #1047 SUPERSTORE')
    ,('1 Stop Shop #3')
    ,('1 Stop Shop #17')
    ,('You 2 Me #16');
    
    select
        SUBSTRING(MyString,CHARINDEX('#',MyString,0) + 1,case when PATINDEX('%[^0-9]%',RIGHT(MyString,LEN(MyString) - CHARINDEX('#',MyString,0))) = 0 then 99 else PATINDEX('%[^0-9]%',RIGHT(MyString,LEN(MyString) - CHARINDEX('#',MyString,0))) - 1 end)
        --char version...
       ,SUBSTRING(MyString,CHARINDEX('#',MyString,0) + 1,case when PATINDEX('%[^0-9]%',substring(MyString,CHARINDEX('#',MyString,0) + 1,LEN(MyString) - CHARINDEX('#',MyString,0) + 1)) = 0 then 99 else PATINDEX('%[^0-9]%',substring(MyString,CHARINDEX('#',MyString,0) + 1,LEN(MyString) - CHARINDEX('#',MyString,0) + 1)) - 1 end)
    
    from
        @t