Sql Server:where 条件中条件表达式的替代方案

发布于 2024-11-08 12:52:13 字数 604 浏览 0 评论 0原文

在编写客户端服务器应用程序时,通常会遇到需要执行一项查询并根据登录用户返回不同记录的情况。

我使用这种方法,但我想知道是否有替代方案,您可以建议吗?

(我问的原因是,对于更复杂的查询,这变得非常不可读,而对于一些 CASE 语句,它会更好)。

declare @UserIsAdministrator bit;
declare @UserID integer; 
set @UserIsAdministrator = 0 -- test value 
set @UserID = 41;            -- test value 

SELECT * FROM employees  
WHERE 
    (@UserIsAdministrator = 1) -- if user is admin return all records
  OR 
    (
       (@UserIsAdministrator = 0) 
     AND 
       (manager_ID = @UserID)
    )                          -- if user is not admin return only "his" records

By writing client server applications typically one stumbles in cases where he needs to do a query that returns different records according to which is the logged in user.

I use this approach, but I wonder if there are alternatives, may you suggest?

(the reason I ask is that for more complx queries this becomes quite unreadable, while with some CASE statements it would be better).

declare @UserIsAdministrator bit;
declare @UserID integer; 
set @UserIsAdministrator = 0 -- test value 
set @UserID = 41;            -- test value 

SELECT * FROM employees  
WHERE 
    (@UserIsAdministrator = 1) -- if user is admin return all records
  OR 
    (
       (@UserIsAdministrator = 0) 
     AND 
       (manager_ID = @UserID)
    )                          -- if user is not admin return only "his" records

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

聚集的泪 2024-11-15 12:52:13

我想我会尽量避免在 SQL 查询中完全嵌入这种类型的授权。在选择要执行的查询之前,拥有单独的查询,并在单独的层/组件中解析角色和权限。

I think I would try to avoid embedding this type of authorization within the SQL queries altogether. Have separate queries, and resolve roles and privileges in a separate layer/component before you select which query to execute.

情场扛把子 2024-11-15 12:52:13

选项:

IF 和 ELSE

IF @UserIsAdministrator = 1
    SELECT * FROM employees
ELSE
    SELECT * FROM employees WHERE manager_ID = @UserID

根据另一个参数

IF @UserIsAdministrator = 1
    SET @UserID = NULL

SELECT * FROM employees  
WHERE manager_ID = ISNULL(@UserID,  manager_ID)

或不同的视图/存储过程更改参数

Options:

IF and ELSE

IF @UserIsAdministrator = 1
    SELECT * FROM employees
ELSE
    SELECT * FROM employees WHERE manager_ID = @UserID

Change parameters based on another parameter

IF @UserIsAdministrator = 1
    SET @UserID = NULL

SELECT * FROM employees  
WHERE manager_ID = ISNULL(@UserID,  manager_ID)

Or different views/stored procs

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文