A friend make a great function that do a sequence combination, and after a little thought I said lets shared with the world as this could be a good example of cte recursion.
Cheers,
declare
@String VARCHAR(8000) = 'Hello how do you do today',
@Delimiter CHAR = ' ',
@n INT = 9
--output
declare @List TABLE (
Word VARCHAR(800),
WordNum INT,
n INT
)
DECLARE
@Iterator INT = 1,
@Word VARCHAR(800) = '',
@Pos INT = 1
;
DECLARE @Temp TABLE (
Word VARCHAR(800),
WordNum INT,
n INT
)
SET @String = REPLACE(LTRIM(RTRIM(@String)),' ',' ');
WHILE @Pos > 0
BEGIN
SET @Pos = CHARINDEX(@Delimiter, @String)
IF @Pos > 0
BEGIN
SET @Word = SUBSTRING(@String,0,@Pos)
SET @String = RIGHT(@String, LEN(@String)- @Pos)
END
ELSE
BEGIN
SET @Word = @String;
END
INSERT INTO @Temp(Word, WordNum) VALUES(@Word, @Iterator);
SET @Iterator = @Iterator + 1;
END
;
WITH cte AS(
SELECT CAST(cte.Word AS VARCHAR(800)) AS Word,
cte.WordNum,
1 AS n
FROM @Temp cte
UNION ALL
SELECT CAST(cte.Word + @Delimiter + l.Word AS VARCHAR(800)) AS Word,
l.WordNum,
cte.n + 1
FROM cte
INNER JOIN @Temp l
ON cte.WordNum + 1 = l.WordNum
WHERE cte.n < @n
)
INSERT INTO @List(Word, WordNum, n)
SELECT Word, WordNum, n
FROM cte
ORDER BY n, WordNum
select * from @List
;
No comments:
Post a Comment