如何将多行子查询的行与要在 In in T-sql 中使用的条件语句组合

how to combine the rows of a multi row sub query with a conditional statement to be used in In in T-sql

我正在尝试从视图 PayrollView 中获取父部门的记录(如果存在)以及提供的子部门 DepartmentSecurityMode=2。行按父部门 ID 过滤。这是我尝试过的,但它向我显示了错误

"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."

DECLARE @LoggedInUserId   UNIQUEIDENTIFIER
                         = 'ff333441-bc4f-4f3d-b992-aad17baa9ebc'
DECLARE @LoggedInRoleId   UNIQUEIDENTIFIER
                         = '2cb31771-7cbc-4f38-b558-804308d908c7'
DECLARE @DepartmentId   UNIQUEIDENTIFIER
                       = '989fd98a-33ae-4ce1-8bbd-ed51ac46137d'
DECLARE @PeriodId   UNIQUEIDENTIFIER = 'e7e52d21-90ad-4f2d-adc2-3f5399a032dd'

SELECT *
FROM PayrollView pv
INNER JOIN Departments d
ON pv.DepartmentId = d.SysId
CROSS JOIN AppRoles r
LEFT JOIN UserDepartmentView rd
ON d.SysId = rd.DepartmentId
AND rd.RoleId = @LoggedInRoleId
AND rd.UserId = @LoggedInUserId
WHERE PeriodId = @PeriodId
AND r.SysId = @LoggedInRoleId
AND 
(
    r.DepartmentSecurityMode = 2
    AND D.SysId IN
    ( 
        (
            SELECT SysId
            FROM Departments ds
            WHERE ds.ParentHierarchy LIKE
             '%' + cast (@DepartmentId AS VARCHAR (50)) + '%'
        )
        ,
        --This is where I want to combine both the child as well the parent.
        (
            CASE
                WHEN @DepartmentId = '00000000-0000-0000-0000-000000000000' THEN D.SysId
                ELSE @DepartmentId
            END
        )
    )
)

非常感谢任何建议。

您正在尝试一些奇怪的事情:使用条件 <expression> IN (...) 您可以过滤项目列表中存在的记录。该列表可以是由逗号或子查询分隔的值。你正在结合这两者(据我所知)是不可能的。

所以你必须将这两种技术分开...

更新:

@JohnLBevan 的回答是一个选项,但我认为您可以通过这样做来简化逻辑:

AND (
      -- don't filter if no department provided 
      @DepartmentId = '00000000-0000-0000-0000-000000000000'

      OR 

      -- filter on the given department
      D.SysId IN ( 
                    SELECT SysId
                    FROM Departments ds
                    WHERE ds.ParentHierarchy LIKE '%' + cast (@DepartmentId AS 
VARCHAR (50)) + '%'
                  )
)

我不完全理解您的要求,但正如 在他的回答中指出的那样,您的 IN 声明存在问题。 尝试用此代码替换 D.SysId in 的逻辑/让我们知道这是否符合您的期望...

AND D.SysId IN
( 
    SELECT SysId
    FROM Departments ds
    WHERE ds.ParentHierarchy LIKE '%' + cast (@DepartmentId AS VARCHAR (50)) + '%'

    UNION

    SELECT CASE
        WHEN @DepartmentId = '00000000-0000-0000-0000-000000000000' THEN D.SysId
        ELSE @DepartmentId
    END
)