Find if a string contains numeric sequences

I am trying to find a query that can determine if there is a sequence of numbers of 3 or more numbers in a string (varchar). This is for SQL Server

Example row: "521324567" This data row will be returned because it has the sequence "4567".

Example line: "410747823" This data line will not be returned because there is no sequence of 3 or more numbers.

Example row: "1274563619" This data row will be returned since it has the sequence "456".

I think that I could probably compute something similar to sql below if it were a fixed-length string.

Select num from numbers where substring(num,2,1)=
(select substring(num,1,1)) + 1
+4
source share
3 answers

7 , :

select num
from numbers
where num like '%123%'
   or num like '%234%'
   or num like '%345%'
   or num like '%456%'
   or num like '%567%'
   or num like '%678%'
   or num like '%789%'

012, .

+4

. , .

DECLARE @MyNum NVARCHAR(50) = '1274563619'

;WITH CTE
AS
(
    SELECT
       SeqNo = 1,
       MyNum = @MyNum,
       PosNum = SUBSTRING(@MyNum,1,1)
    UNION ALL
    SELECT
       SeqNo = SeqNo +1,
       MyNum,
       PosNum = SUBSTRING(MyNum,SeqNo,1)
       FROM CTE
          WHERE SeqNo <= LEN(@MyNum)
)
SELECT
    MyNum
    FROM CTE C1
       WHERE EXISTS
       (
          SELECT 1 FROM CTE C2
             WHERE 
                (
                    C2.SeqNo = C1.SeqNo+1 
                    AND
                    C2.PosNum = C1.PosNum+1
                )
                OR
                (
                    C2.SeqNo = C1.SeqNo+2 
                    AND
                    C2.PosNum = C1.PosNum+2
                )
       )
       GROUP BY MyNum
          HAVING COUNT(1)>2
+1

Bohemian is correct, but here is an option for a picklist:

select num, case when 
   num like '%012%'
   or num like '%123%'
   or num like '%234%'
   or num like '%345%'
   or num like '%456%'
   or num like '%567%'
   or num like '%678%'
   or num like '%789%'
   or num like '%890%'
   or num like '%901%' 
then 'Yep' else 'Nope' end as is_there_a_sequence
from numbers

I also added 012and 890. Although it 901may be a bridge too far.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1693897/


All Articles