在CTE中使用LENGTH

时间:2014-01-17 05:38:44

标签: sql sql-server common-table-expression

SQL中LENGTH的用途是什么。您可以参考以下CTE查询来回答

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

2 个答案:

答案 0 :(得分:0)

WITH ShowMessage(STATEMENT, LENGTH)

在此部分查询中,您分配了第一个和第二个列名称。 长度只是一个别名。

类似于:

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

答案 1 :(得分:0)

声明CTE有两种“样式” - 就列命名/别名而言。据我所知,差异严格来说是美化的;

------------------
--  Style 1
--  Alias inside
------------------
;WITH MyCTE AS
(
    SELECT   FirstName  = fn
            ,LastName   = sn
    FROM MyTable
)
...
------------------
--  Style 2
--  Alias outside
------------------
;WITH MyCTE (FirstName, LastName) AS
(
    SELECT   fn
            ,sn
    FROM MyTable
)
...