SQL Repeating Character String

老子叫甜甜 提交于 2019-12-02 12:57:35

The following finds patterns i.e. 333... or 123... or 987...

Think of it like Rummy 500... Runs and groups of 3's or more.

Declare @Table table (col int)
Insert into @Table values
(4141243),(4290577),(98765432),(78635389),(4141243),(22222),(4290046),(55555555),(4141243),(6789),(77777),(45678),(4294461),(55555),(4141243),(5555)

Declare @Num table (Num int);Insert Into @Num values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)

Select Distinct A.*
  From @Table A
  Join (
        Select Patt=replicate(Num,3) from @Num
        Union All
        Select Patt=right('000'+cast((Num*100+Num*10+Num)+12 as varchar(5)),3) from @Num where Num<8
        Union All
        Select Patt=reverse(right('000'+cast((Num*100+Num*10+Num)+12 as varchar(5)),3)) from @Num where Num<8
       ) B on CharIndex(Patt,cast(col as varchar(25)))>0

Returns

col
5555
6789
22222
45678
55555
77777
55555555
98765432

Now, If you don't care to identify "runs" (123...)", just remove the following:

    Union All
    Select Patt=right('000'+cast((Num*100+Num*10+Num)+12 as varchar(5)),3) from @Num where Num<8
    Union All
    Select Patt=reverse(right('000'+cast((Num*100+Num*10+Num)+12 as varchar(5)),3)) from @Num where Num<8

As you are only interested in complete repeatings, such as '3333' and not in, say, '43333', this is rather simple: Find strings longer than one character, where you end up with an empty string when you remove all characters that equal the first one:

select *
from mytable 
where len(value) > 1 and len(replace(value, left(value,1), '')) = 0

You can do this in one case statement

select val, 
(case when len(val) > 1 and len(replace(val,left(val,1),'')) = 0 then 'Yes' else 'No' end) as repeating_characters
from (values 
('00000'),
('222222222'),
('333'),
('11211')
) as q(val);

Gives:

val        repeating_characters
---------  --------------------
00000      Yes
222222222  Yes
333        Yes
11211      No

First a check if the length of value is greater than 1. If so, then isn't an empty string or just one character.

Then take the first character and replace all of that character with nothing in the value.
If the length of the remaining is bigger than 0 then there's more than 1 kind of character.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!