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

前端 未结 5 722
孤街浪徒
孤街浪徒 2021-02-12 09:53

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:39

    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.

提交回复
热议问题