我想一次选择deptUserCount
和childDeptCount
。
ALTER PROCEDURE [dbo].[sp_dept_user_select]
@dept_no INT,
@company_no INT
AS
BEGIN
SET NOCOUNT ON;
SELECT
( SELECT COUNT(U.user_no)
FROM [dbo].[tb_user] U WITH(NOLOCK)
INNER JOIN [dbo].[tb_dept_user] DU WITH(NOLOCK)
ON U.user_no = DU.user_no
WHERE DU.dept_no = @dept_no
AND U.company_no = @company_no
AND U.user_level < 200
) AS deptUserCount
,( WITH tblChild 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 tblChild
ON D.parent_dept_no = tblChild.dept_no
WHERE D.company_no = 1
)
SELECT COUNT(D.dept_no)
FROM [dbo].[tb_dept] D WITH(ROWLOCK)
WHERE dept_no IN (SELECT dept_no FROM tblChild)
) AS childDeptCount
END
这是我现在编写的代码。但是WITH语句出现错误,提示
不正确的语法错误我该如何解决该错误? 还是我必须做一个单独的过程才能得到我想要的东西?
答案 0 :(得分:1)
您应该尝试这样的事情
WITH
deptUserCount AS (
SELECT ...
),
tblChild AS (
SELECT ...
UNION ALL
SELECT ... FROM tblChild ...
)
SELECT ...
FROM tblChild JOIN deptUserCount...
答案 1 :(得分:1)
您可以尝试以下操作
with deptUserCount as
( SELECT COUNT(U.user_no) as dptcount
FROM [dbo].[tb_user] U WITH(NOLOCK)
INNER JOIN [dbo].[tb_dept_user] DU WITH(NOLOCK)
ON U.user_no = DU.user_no
WHERE DU.dept_no = @dept_no
AND U.company_no = @company_no
AND U.user_level < 200
) ,tblChild 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 tblChild
ON D.parent_dept_no = tblChild.dept_no
WHERE D.company_no = 1
), childDeptCount as
(
SELECT COUNT(D.dept_no) as childdptCnt
FROM [dbo].[tb_dept] D WITH(ROWLOCK)
WHERE dept_no IN (SELECT dept_no FROM tblChild)
) select a.childdptCnt,b.dptcount from childDeptCount a,deptUserCount b