1

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

在员工表中,这由名为 Internal 的列表示,用 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  
4

1 回答 1

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;

在这里提琴

于 2013-02-28T13:09:57.567 回答