Search code examples
sqlnumbersvarchar

Finding first four numbers inside varchar in SQL


I have to find the first sequence of four numbers inside a table using SQL.

    RVSP_040517.M
    SERIES_040517_CP.TXT
    SAUDE_O10N0505.M
    SERIES_040517.txt
    RVSP_080517.M
    SERIES_080517_CP.TXT

As we can see, there is groups of numbers before, but the first group of four numbers is what I want.

How can I do it?

The result I am expecting from this table is:

    0405
    0405
    0505
    0405
    0805
    0805

I was trying to use PADINDEX but it wasn't working


Solution

  • With "PADINDEX" you probably mean PATINDEX; With this function you can find the index of the first occurrence of a pattern in a string, and this can help you extracting the first four consecutive digits:

    SELECT (case when (PATINDEX('%[0-9][0-9][0-9][0-9]%', a)=0) then NULL else substring(a,PATINDEX('%[0-9][0-9][0-9][0-9]%', a),4) end) as digits
    FROM (VALUES ('RVSP_040517.M'), ('SERIES_040517_CP.TXT'), ('SAUDE_O10N0505.M'), ('NO_4_DIGITS')) AS MyTable(a)