我想两次使用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
的所有列。我该怎么办?
答案 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)
。除非您非常非常了解自己在做什么,否则不要使用这些提示。