sql server:用重复的char查找名称

时间:2017-11-08 11:06:22

标签: sql sql-server regex

我想在其中找到带有重复字符的名称,例如:

  • ANA
  • asdbbiop
  • a1for1
  • @邮件@禁

我在这里发现了一个类似的问题,但它们是连续的。

我知道2:

1.使用帮助表并加入

2.a很长"喜欢"声明

有没有办法用正则表达式做到这一点?

1 个答案:

答案 0 :(得分:1)

此代码可帮助您找到在单词和字符数中找到的重复字符

样本数据

    DECLARE @Table TABLE (ID INT,String nvarchar(100))
    INSERT INTO @Table
    SELECT 1,'ana'          UNION ALL
    SELECT 2,'asdbbiop'     UNION ALL
    SELECT 3,'a1for1'       UNION ALL
    SELECT 4,'@mail@ban'

    SELECT  * FROM @Table

使用Recursive Cte​​我们得到预期的结果

;With cte
AS
(
SELECT ID, String
        ,CAST(LEFT(String,1)AS VARCHAR(10)) AS Letter
        ,RIGHT(String,LEN(String)-1)  AS Remainder 
FROM @Table
WHERE LEN(String)>1

UNION ALL
SELECT ID, String
        ,CAST(LEFT(Remainder,1)AS VARCHAR(10)) AS Letter
        ,RIGHT(Remainder,LEN(Remainder)-1)  AS Remainder 
FROM cte
WHERE LEn(Remainder)>0
)
SELECT ID,
       String, 
       letter, 
       Ascii(letter) AS CharCode, 
       Count(letter) AS CountOfLetter 
FROM   cte 
GROUP  BY ID,
          String, 
          letter, 
          Ascii(letter) 
HAVING COUNT(letter)>1

结果

ID  String  letter  CharCode    CountOfLetter
---------------------------------------------
1   ana         a     97          2
2   asdbbiop    b     98          2
3   a1for1      1     49          2
4   @mail@ban   @     64          2
4   @mail@ban   a     97          2