SQL Server中Oracle的CONNECT BY PRIOR模拟

2022-01-31 00:00:00 sql-server-2005 sql-server

如何在 SQL Server 2000/2005/2008 中获得 CONNECT BY PRIOR of Oracle 的功能?

How can I get the functionality of CONNECT BY PRIOR of Oracle in SQL Server 2000/2005/2008?

推荐答案

实现递归查询的 SQL 标准方式,例如实现IBM DB2 和 SQL Server 是 WITH代码>子句.请参阅 这篇文章,了解翻译 的一个示例CONNECT BY 转换成 WITH(技术上是一个递归 CTE)——该示例适用于 DB2,但我相信它也适用于 SQL Server.

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

显然,原始的 querant 需要一个特定的示例,这是来自 IBM 站点的一个示例,其 URL 我已经给出了.给定一张桌子:

apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

其中mgrid 引用员工经理的empid,任务是获取直接或间接向Joan 报告的每个人的姓名.在 Oracle 中,这是一个简单的 CONNECT:

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

在 SQL Server、IBM DB2 或 PostgreSQL 8.4 中(以及在 SQL 标准中,值得一提的是;-),完全等效的解决方案是递归查询(更复杂的语法,但实际上更力量和灵活性):

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle 的 START WITH 子句成为第一个嵌套 SELECT,即递归的基本情况,将与递归部分进行 UNION只是另一个SELECT.

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server 的 WITH 的特定风格当然记录在 MSDN,其中还给出了使用此关键字的指导方针和限制,以及几个示例.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

相关文章