SQL Server 2008R2 Where子句合并两个查询

时间:2013-02-28 13:05:22

标签: sql sql-server-2008-r2

我有一个查询,可以获取用户有权访问的商店列表。 如果用户是内部员工,他们可以自动访问所有商店。

在员工表中,这由一个名为Internal的coloumn表示,其中1表示内部员工,0表示不是内部员工。

目前有一个存储过程,它获取传入userId的用户的存储列表。存储的过程类似于下面的过程。所以我想弄清楚如何将查询加入其中。

    DECLARE @IsInternal bit

    SELECT @IsInternal = Staff.Internal FROM Staff WHERE Staff.StaffId = @userId

 IF(@IsInternal = 0)
   BEGIN
      SELECT DISTINCT Store.Id, Store.Name,
      FROM 
        Store JOIN StaffAccess ON StaffAccess.StoreID = Store.StoreId
              JOIN Staff ON StaffAccess.StaffId= Staff.StaffId
      WHERE
        StaffAccess.StaffID = @userId
      ORDER BY
          Store.Name
   END
ELSE
   BEGIN
        SELECT DISTINCT Store.Id,Store.Name,
        FROM Store
        ORDER BY Store.Name
  END

抱歉,我应该包含一个员工访问表。如果我在下面运行它会为非内部员工的用户带回所有商店

SELECT DISTINCT
        Store.Id,
        Store.Name,

    FROM
        Store
            JOIN StaffAccess ON StaffAccess.StoreID = Store.StoreId
            JOIN Staff on Staff.Internal= 1 OR (StaffAccess.StaffID = @userId        AND StaffAccess.StaffId = Staff.StaffId)   

    ORDER BY
        Store.Name  

1 个答案:

答案 0 :(得分:2)

您可以使用这个简单的查询来解决您的要求

SELECT DISTINCT
     Store.storeid,
     Store.Name 
FROM
    Store JOIN Staff ON Staff.StaffID = @UserId 
    AND (Staff.Internal = 1 OR 
         Staff.StoreID = Store.StoreId)
ORDER BY
    Store.Name;

小提琴here