sql >> Database teknologi >  >> RDS >> Sqlserver

Udtræk tal fra en tekst i SQL Server

Dette er lidt kortere. Omdannet det til Inline Table Function, der bruger en rekursiv CTE til at finde tallene.

create function [dbo].[GetNumbersFromText](@String varchar(2000))
returns table as return
(
  with C as
  (
    select cast(substring(S.Value, S1.Pos, S2.L) as int) as Number,
           stuff(s.Value, 1, S1.Pos + S2.L, '') as Value
    from (select @String+' ') as S(Value)
      cross apply (select patindex('%[0-9]%', S.Value)) as S1(Pos)
      cross apply (select patindex('%[^0-9]%', stuff(S.Value, 1, S1.Pos, ''))) as S2(L)
    union all
    select cast(substring(S.Value, S1.Pos, S2.L) as int),
           stuff(S.Value, 1, S1.Pos + S2.L, '')
    from C as S
      cross apply (select patindex('%[0-9]%', S.Value)) as S1(Pos)
      cross apply (select patindex('%[^0-9]%', stuff(S.Value, 1, S1.Pos, ''))) as S2(L)
    where patindex('%[0-9]%', S.Value) > 0
  )
  select Number
  from C
)

Hvis du forventer at have mere end 100 numre i strengen, skal du kalde den med option (maxrecursion 0) .

declare @S varchar(max)
set @S = 'Give me 120 this week and 50 next week'
select number from GetNumbersFromText(@S) option (maxrecursion 0)


  1. Hvorfor tager Microsoft SQL Server 2012-forespørgsler minutter over JDBC 4.0, men sekund(er) i Management Studio?

  2. Mere effektivt at have flere kolonner eller flere rækker?

  3. Hvordan Cosh() virker i PostgreSQL

  4. konvertering af Epoch-tidsstempel til sql-server (læsbart format for mennesker)