Aparan
Aparan

Reputation: 1273

Common table expressions- recursive call

I found this piece of code here

WITH ShowMessage(STATEMENT, LENGTH)
AS
(
SELECT STATEMENT = CAST('I Like ' AS VARCHAR(300)), LEN('I Like ')
UNION ALL
SELECT
CAST(STATEMENT + 'CodeProject! ' AS VARCHAR(300))
, LEN(STATEMENT) FROM ShowMessage
WHERE LENGTH < 300
)
SELECT STATEMENT FROM ShowMessage

Output:

enter image description here

I can't get the meaning of the code correctly, especially the usage of length.

Upvotes: 0

Views: 50

Answers (1)

Adriaan Stander
Adriaan Stander

Reputation: 166376

Have a look at the query results when you change it to include the LENGTH column.

WITH ShowMessage(STATEMENT, LENGTH)
AS
(
    SELECT  STATEMENT = CAST('I Like ' AS VARCHAR(300)), 
            LEN('I Like ')
    UNION ALL
    SELECT  CAST(STATEMENT + 'CodeProject! ' AS VARCHAR(300)), 
            LEN(STATEMENT) FROM ShowMessage
    WHERE   LENGTH < 300
)
SELECT  STATEMENT,
        LENGTH
FROM    ShowMessage

You will notice on each recursion the length of the string gets longer.

The recursice loops will end once the leng grows to longer than 300

Upvotes: 2

Related Questions