'START WITH' MS-SQL 中的等效表达式
'START WITH' equivalent expression in MS-SQL
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;
如果 table 包含分层数据,那么您可以使用分层查询子句按分层顺序 select 行。
START WITH
指定层次结构的根行。
CONNECT BY
指定层次结构的父行和子行之间的关系。
是否有 MS-SQL 的等效表达式?
不直接。您可以像下面这样使用递归 CTE(常见的 table 表达式),这需要多写一点:
;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
需要稍微回顾一下递归连接的列,但您应该明白了。
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;
如果 table 包含分层数据,那么您可以使用分层查询子句按分层顺序 select 行。
START WITH
指定层次结构的根行。
CONNECT BY
指定层次结构的父行和子行之间的关系。
是否有 MS-SQL 的等效表达式?
不直接。您可以像下面这样使用递归 CTE(常见的 table 表达式),这需要多写一点:
;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
需要稍微回顾一下递归连接的列,但您应该明白了。