Sqlserver
 sql >> Baza danych >  >> RDS >> Sqlserver

Wyodrębnij liczby z tekstu w SQL Server

To jest trochę krótsze. Przekształcono go w funkcję Inline Table, która używa rekurencyjnego CTE do znajdowania liczb.

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
)

Jeśli spodziewasz się, że w ciągu będzie więcej niż 100 liczb, musisz wywołać to za pomocą 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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. SQL Server — PRZED WSTAWIENIEM wyzwalacza

  2. Ms SQL geography.STDistance zwraca nieprawidłową odległość

  3. Różnica między Equi-Join i Inner-Join w SQL

  4. SQL Server 2008 - utwórz skrypt bazy danych (schemat + dane) za pomocą wiersza poleceń

  5. Dołączanie do SQL Server 2008