公用表表达式 - 递归调用

时间:2013-05-30 04:17:13

标签: sql sql-server

我发现了这段代码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

输出:

enter image description here

我无法正确理解代码的含义,尤其是长度的使用。

1 个答案:

答案 0 :(得分:2)

当您将查询结果更改为包含LENGTH列时,请查看查询结果。

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

您会注意到每次递归时字符串的长度变长。

一旦leng增长到超过300

,递归循环将结束