DECLARE @vtext VARCHAR(255)
SET @vtext = 'abcbklmnodfghijkmer'
/*讲字符串转成一列存储,并生成行号*/
WITH x0
AS ( SELECT number AS id ,
SUBSTRING(@vtext, number, 1) AS letter
FROM master.dbo.spt_values
WHERE type = 'P'
AND number = LEN(@vtext)
AND number >= 1
),/*实现计数器*/
x1 ( id, letter, clen )
AS ( SELECT id ,
letter ,
1 AS clen
FROM x0
WHERE id = 1
UNION ALL
SELECT x0.id ,
x0.letter ,
CASE WHEN x1.letter = x0.letter THEN x1.clen + 1
ELSE 1
END AS clen
FROM x0 ,
x1
WHERE x0.id = x1.id + 1
)
/*截取字符串*/
SELECT SUBSTRING(@vtext, start, sublen) AS 最大子序列
FROM ( SELECT id ,
clen ,
MAX(clen) OVER ( ) AS maxclen ,
id - MAX(clen) OVER ( ) + 1 AS start ,
MAX(clen) OVER ( ) AS sublen
FROM x1
) t
WHERE clen = maxclen