【问题标题】:IF ELSE Statement in WHERE Clause SQLWHERE 子句 SQL 中的 IF ELSE 语句
【发布时间】:2015-05-24 05:35:53
【问题描述】:

我想从 sql 中实现以下功能,假设我在存储过程中有 @accountId int 作为参数,现在如果我将参数作为 99999 传递,那么在所有选择语句中它选择 WHERE AccountId <> 124 否则如果我传递任何其他参数它选择WHERE AccountId=@accountId。这个语句是一个很长的存储过程的一部分,所以我没有包含整个过程。

WHERE (IF(AccountId = 99999) 
       BEGIN
          AccountId <> 124
       END
       ELSE
       BEGIN
          AccountId = @accountId
       END)

或者我可以从 CASE 声明中获得类似的结果吗? 有点像,

WHERE (AccountId(CASE(AccountId) WHEN 99999 THEN <>124 ELSE =@accountId))

我已经编辑了我的问题,对于以不相关的方式提出问题,我深表歉意。请让我知道这对您是否有意义或您需要任何进一步的信息。

【问题讨论】:

  • 您可能需要考虑使用NULL 而不是幻数 来表明您不想过滤AccountId:where ( @AccountId is NULL and AccountId &lt;&gt; 124 ) or ( @AccountId is not NULL and AccountId = @AccountId )。跨度>

标签: tsql sql-server-2012


【解决方案1】:
WHERE (AccountId =  1 and  SenderId <> 10) 
   or (AccountId <> 1 and  SenderId =  10) 

WHERE (@AccountId =  9999 and  SenderId <> 10) 
   or (@AccountId <> 9999 and  SenderId =  @AccountId)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    相关资源
    最近更新 更多