使用And,Or运算符(SQL)无法获得预期的结果

时间:2014-08-28 23:33:43

标签: sql sql-server-2008 operators parameter-passing case

 `DECLARE      @Username NVARCHAR(MAX),
                @EmployeeTypeID INT
        SET @Username       =  'User\Stephen'
        SET @EmployeeTypeID = 4

        SELECT 
        ER.RoleID AS [Manager Role ID], 
        E.Name AS [Manager],
        AR.RoleID AS [Employee Role ID],
        A.Name AS [Employee], 

                    --Manager table
        FROM        Employee                E   
                    --Employee and Manager mapping table
        Left Join  Managers                M   ON (E.EmployeeId = M.ManagerId)
                    --Employee table (For Manager's subordinate)
        Left Join  Employees               A   ON (A.EmployeeId = M.EmployeeId)
                    --Role table (For Manager Role mapping)
        Left Join  Roles                   ER  ON (M.ManagerId = ER.EmployeeId)
                    --Role table (For Employee/subordinate Role mapping)
        Left Join  Roles                   AR  ON (M.EmployeeId = AR.EmployeeId)

        WHERE 
            -- Active Filter
            E.Active = 1
            AND A.Active = 1
            AND M.Active = 1
            -- Get Username
            AND E.Username = substring(@Username, CHARINDEX('\',@Username) + 1, 100)

            --Employee Type Filter
            AND         
                (
                    (
                            @EmployeeTypeID =   1

                        and
                            AR.RoleId   IN  ('1')   
                        and 
                            ER.RoleId   IN  ('2')
                    )
                    or
                    (
                            @EmployeeTypeID =   2
                        and
                            AR.RoleId   IN  ('1','2')
                        and 
                            ER.RoleId   IN  ('2','3')
                    )
                    or
                    (
                            @EmployeeTypeID =   4
                        and
                            AR.RoleId   IN  ('1','2')
                        and 
                            ER.RoleId   IN  ('2','13')
                    )
                    or
                    (
                            @EmployeeTypeID =   8
                        and
                            AR.RoleId   IN  ('1','2','13')
                        and 
                            ER.RoleId   IN  ('2','13','3')
                    )
                )`

问题:

我尝试使用AND-OR运算符来尝试复制Case语句,但这次我希望数据结果包含所有Managers和Employees。

具有基于@Username分配的RoleID和Manager(请参阅“员工类型过滤器”部分)。我不确定为什么它没有显示预期的数据结果。如果有人能突出我错过的问题,那将非常有帮助。 TIA!

应该做什么:

根据经理和员工角色的集合显示分配给经理(@Username)的员工。

数据结果预期:

@Username = Mr C   
@EmployeeTypeID = 2

Table image

0 个答案:

没有答案