【问题标题】:'START WITH' equivalent expression in MS-SQLMS-SQL 中的“START WITH”等效表达式
【发布时间】:2018-03-21 10:56:25
【问题描述】:

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 的等效表达式?

【问题讨论】:

    标签: sql-server oracle tsql connect-by


    【解决方案1】:

    不直接。您可以使用递归 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
    

    需要稍微回顾一下递归连接的列,但你应该明白了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2016-10-14
      相关资源
      最近更新 更多