使用Inline Select在运算符中使用
我想根据运行 SP
的人员从一个表中进行选择。例如,如果执行者具有管理
角色,他们可以看到所有记录,但如果执行者是员工
,那么他们只能看到所有员工的记录。有一些角色,例如 Seller
、StockKeeper
等。
请考虑这个 sudo 代码,我想编写这样的代码,但我收到错误:
Declare @Role varchar(30)
select *
from MyTable
where Status in (IIF(@Role = 'Employee', select -1 , select -1, 0, 1))
OR
select *
from MyTable
where Status in (case @Role when 'Employee' then select -1 else select -1, 0 , 1 end)
错误:
关键字“select”附近的语法不正确。
关键字“else”附近的语法不正确。
“)”附近的语法不正确。
有没有办法结合内联 SELECT 和 IN 运算符?
谢谢
编辑1)
示例数据:
Id Value Status
----------------------------
1 10 -1
2 20 0
3 30 -1
4 40 1
5 50 -1
6 60 0
7 70 1
8 80 -1
对于Employee
,我想得到这个结果:
Id Value Status
----------------------------
1 10 -1
3 30 -1
5 50 -1
8 80 -1
对于Manager
,我想获取所有记录。
I want to select from one table based on who run the SP
. For example if executer has Management
role the they can see all records but if executer is Employee
then they just see records for all employees. There are some roles like Seller
, StockKeeper
, ... .
Please consider this sudo code, I want to write a code like this but I got error:
Declare @Role varchar(30)
select *
from MyTable
where Status in (IIF(@Role = 'Employee', select -1 , select -1, 0, 1))
OR
select *
from MyTable
where Status in (case @Role when 'Employee' then select -1 else select -1, 0 , 1 end)
Error:
Incorrect syntax near the keyword 'select'.
Incorrect syntax near the keyword 'else'.
Incorrect syntax near ')'.
Is there any way to combine inline SELECT
and IN
operator?
Thanks
Edit 1)
Sample Data:
Id Value Status
----------------------------
1 10 -1
2 20 0
3 30 -1
4 40 1
5 50 -1
6 60 0
7 70 1
8 80 -1
for Employee
I want to get this result:
Id Value Status
----------------------------
1 10 -1
3 30 -1
5 50 -1
8 80 -1
for Manager
I want to get All records.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
Union
以有条件的方式构建允许状态的完整列表:假设您的示例数据反映了您可以简化的更大图片,
请记住:
case
< /a>是表达式IE返回标量值。它不是开关语句。case
允许它,您仍然需要(SELECT -1)
而不是选择-1
。Use
UNION
to build the full list of allowable statuses in a conditional manner:Assuming your sample data is reflective of the bigger picture you could simplify that down to:
Notes:
CASE
is an expression i.e. returns a scalar value. Its not a switch statement.case
allowed it you would still need(select -1)
rather thanselect -1
.如果我正确理解,您可以尝试使用条件来判断您的预期结果。
如果您的输入
@Role
是Manager
获取所有数据,否则雇员
将获得-1
If I understand correctly, you can try to use conditions to judge your expected result.
if your input
@Role
isManager
get all data, otherwiseEmployee
will get-1
sqlfiddle