在MS-SQL中'START WITH'等效表达式

时间:2018-03-21 10:56:25

标签: sql-server oracle tsql connect-by

Oracle SQL支持START WITH表达式。 例如,

CREATE VIEW customers AS
SELECT LEVEL lvl, customer_code, customer_desc, customer_category 
FROM customers_master
START WITH some_column = '0'
CONNECT BY PRIOR CUSTOMER_CODE = PARENT_CUSTOMER_CODE;

如果表包含分层数据,则可以使用分层查询子句以分层顺序选择行。

START WITH指定层次结构的根行。

CONNECT BY指定父级行与层次结构的子行之间的关系。


是否有MS-SQL的等效表达式?

1 个答案:

答案 0 :(得分:3)

不直接。您可以使用递归CTE(公用表表达式),如下所示,这需要更多的写作:

;WITH RecursiveCTE AS
(
    -- Anchor (START WITH)
    SELECT
        customer_code, 
        customer_desc, 
        customer_category,
        Level = 1
    FROM
        customers_master AS C
    WHERE
        C.some_column = '0'

    UNION ALL

    -- Recursive join
    SELECT
        C.customer_code, 
        C.customer_desc, 
        C.customer_category,
        Level = R.Level + 1
    FROM
        RecursiveCTE AS R -- Note that we are referencing a table that we are just declaring as CTE
        INNER JOIN customers_master AS C ON
            R.CUSTOMER_CODE = C.PARENT_CUSTOMER_CODE
)
SELECT
    R.*
FROM
    RecursiveCTE AS R

需要稍微检查一下递归连接的列,但是你应该明白这一点。