[英]Using CASE expression inside a where clause
I have a stored proc with 2 parameters, both integer我有一个带有 2 个参数的存储过程,两个参数都是 integer
I need to use case statement inside where clause but i could not get it right我需要在 where 子句中使用 case 语句,但我无法正确使用
where
dbo.StockTransfer.BranchId = @branchId
AND
CASE WHEN IsNumeric(@roleId) = 1
THEN
dbo.StockTransfer.StatusId !=12
ELSE
dbo.StockTransfer.StatusId NOT in (12, 13)
END
order by dbo.StockTransfer.StatusId ASC
I am getting an error in 'dbo.StockTransfer.StatusId !=12'我在“dbo.StockTransfer.StatusId !=12”中遇到错误
Msg 102, Level 15, State 1, Procedure GetDeliveryList, Line 44 [Batch Start Line 0]消息 102,级别 15,State 1,过程 GetDeliveryList,第 44 行 [批处理开始行 0]
Incorrect syntax near '.'. '.' 附近的语法不正确。
Don't bother.不要打扰。 Just use regular logic:只需使用常规逻辑:
where dbo.StockTransfer.BranchId = @branchId and
( (IsNumeric(@roleId) = 1 and
dbo.StockTransfer.StatusId <> 12
) or
(IsNumeric(@roleId) = 0 and
dbo.StockTransfer.StatusId not in (12, 13)
)
)
This doesn't handle NULL
values, but that can easily be added.这不处理NULL
值,但可以轻松添加。
Actually, I might simplify this to:实际上,我可以将其简化为:
where dbo.StockTransfer.BranchId = @branchId and
dbo.StockTransfer.StatusId <> 12 and
(IsNumeric(@roleId) = 1 or
dbo.StockTransfer.StatusId <> 13
)
Given the newest comments about what you want to return I think it would be something like this.鉴于有关您要返回的内容的最新评论,我认为它会是这样的。 I added lots of white space for clarity on the parenthesis.为了括号的清晰,我添加了很多空格。
where dbo.StockTransfer.BranchId = @branchId
AND
(
(
@roleId = 1
AND
StatusId in (13, 14)
)
OR
(
@roleId <> 1
AND
StatusId = 14
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.