查询带子句的double

时间:2019-03-05 12:54:10

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

我想两次使用with语句。

WITH userChild AS
(
    WITH deptChild AS
    (
    SELECT dept_no, parent_dept_no, name
    FROM [dbo].[tb_dept] D WITH(NOLOCK)
     WHERE parent_dept_no = 2
     AND D.company_no = 1

      UNION ALL
      SELECT D.dept_no, D.parent_dept_no, D.name
      FROM [dbo].[tb_dept] D  WITH(NOLOCK)
   INNER JOIN deptChild  
   ON D.parent_dept_no = deptChild.dept_no
   WHERE D.company_no = 1
   )
   SELECT user_no
   FROM [dbo].[tb_dept_user] WITH(ROWLOCK)
   WHERE dept_no IN (SELECT dept_no FROM deptChild)
)
SELECT *
FROM [dbo].[tb_user] U WITH(NOLOCK)
WHERE user_no IN (SELECT user_no FROM userChild)

这是我的代码。内部WITH语句从user_no中找到的所有depts中选择deptChild。 tb_user表没有dept_no列。因此,对于从user_no找到的所有deptChild,我想从user_no表中选择该tb_user的所有列。我该怎么办?

1 个答案:

答案 0 :(得分:4)

没有必要这样做。只需链接CTE:

WITH deptChild AS (
      SELECT dept_no, parent_dept_no, name
      FROM [dbo].[tb_dept] D
      WHERE parent_dept_no = 2 AND D.company_no = 1
      UNION ALL
      SELECT D.dept_no, D.parent_dept_no, D.name
      FROM [dbo].[tb_dept] D INNER JOIN
           deptChild  
           ON D.parent_dept_no = deptChild.dept_no
      WHERE D.company_no = 1
    ),
    userChild as (
     SELECT user_no
     FROM [dbo].[tb_dept_user] 
     WHERE dept_no IN (SELECT dept_no FROM deptChild)
    )
SELECT *
FROM [dbo].[tb_user] U
WHERE user_no IN (SELECT user_no FROM userChild);

还要注意,我删除了WITH (NOLOCK)。除非您非常非常了解自己在做什么,否则不要使用这些提示。