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

前端 未结 5 899
难免孤独
难免孤独 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:20

    Maybe a bit complicated but it works for what you need:

    declare @test table(mytext varchar(50))
    
    insert @test values('Washington 40 New Orleans 32')
    insert @test values('Detroit 27 St. Louis 23')
    
    select 
    WinningTeam=SubString(mytext, 0,PatIndex('%[0-9.-]%', mytext)), 
    WinningTeamScore=Left(SubString(mytext, PatIndex('%[0-9.-]%', mytext), 50),PatIndex('%[^0-9.-]%', SubString(mytext, PatIndex('%[0-9.-]%', mytext), 50) + 'X')-1),
    LosingTeam=SubString(mytext, PatIndex('%[0-9.-]%', mytext)+3,PatIndex('%[0-9.-]%', mytext)), 
    LosingTeamScore=reverse(Left(SubString(reverse(mytext), PatIndex('%[0-9.-]%', reverse(mytext)), 50),PatIndex('%[^0-9.-]%', SubString(reverse(mytext), PatIndex('%[0-9.-]%', reverse(mytext)), 50) + 'X')-1)) 
    from @test
    

    The query above works for scores under 100 points but you can modify it to deal with any number.

提交回复
热议问题