简体   繁体   中英

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:

在此输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM