In SQL Server can you find the first number in a string?

前端 未结 5 905
难免孤独
难免孤独 2021-02-12 10:12

I have a varchar(50) sql server column with data like this:

RawData
----------------------------
Washington 40 New Orleans 32
Detroit 27 St. Louis 23
         


        
5条回答
  •  星月不相逢
    2021-02-12 10:24

    Here is a very ugly implementation of PATINDEX() which returns the data in the multiple columns:

    SELECT rtrim(substring(RawData, 1, PATINDEX('%[0-9]%', RawData) -1)) WinningTeam,
        ltrim(rtrim(substring(RawData, PATINDEX('%[0-9]%', RawData), 2))) WinningTeamScore,
        reverse(ltrim(rtrim(substring(reverse(SUBSTRING(RawData, 1, LEN(rawdata) - (PATINDEX('%[aA-zZ]%', REVERSE(rawData)) - PATINDEX('%[0-9]%', reverse(RawData))))), 1, PATINDEX('%[0-9]%', SUBSTRING(RawData, 1, LEN(rawdata) - (PATINDEX('%[aA-zZ]%', REVERSE(rawData)) - PATINDEX('%[0-9]%', reverse(RawData))))))))) LosingTeam,
        substring(reverse(RawData), PATINDEX('%[0-9]%', reverse(RawData)), (PATINDEX('%[aA-zZ]%', REVERSE(rawData)) - PATINDEX('%[0-9]%', reverse(RawData)))) LosingTeamScore
    from yourtable
    

    See SQL Fiddle with Demo

提交回复
热议问题