【问题标题】:SQL Server : conditional in where statement using colunm as a conditionSQL Server:在where语句中使用列作为条件的条件
【发布时间】:2018-08-16 08:27:30
【问题描述】:

如何在where 子句中使用不同的条件列?

请参考下面的代码

if OBJECT_ID('tempdb..#MemberInfo') is not null
drop table #MemberInfo  

DECLARE @GroupID varchar(60),
@Eoid varchar(60);

set @GroupID='23'    
set @Eoid = null;

select a.memberid, a.membername, a.groupid, a.eoid
from membermst a 
where
    case 
       when @GroupID is not null 
          then a.groupid = @GroupID // this is an error
       when @Eoid is not null 
          then a.eoid = @Eoid // this is an error    
       when @GroupID is null and @Eoid is null 
          then select all records // this is an error
end 

这些是我的过滤条件

  • 如果@GroupID 不为空,则查询将基于GroupID 生成
  • 否则,如果@Eoid 不为空,则查询将基于Eoid 生成
  • 否则,如果 GroupID 和 Eoid 均为空,则选择所有记录

注意这是我程序的条件

  1. groupid 和 eoid 可以同时为空
  2. groupid 或 eoid 都只能有一个值
  3. 如果 groupid 有值则 eoid 为空
  4. 如果 eoid 有值则 groupid 为空
  5. groupid 不能同时有值。那么其中任何一个都只有一个值

这可以使用 SQL 查询吗?

【问题讨论】:

    标签: sql sql-server sql-server-2005


    【解决方案1】:

    只需使用常规布尔逻辑:

    select m.memberid, m.membername, m.groupid, m.eoid
    from membermst m
    where (@GroupID is not null and a.groupid = @GroupID) or
          (@GroupID is null and @Eoid is not null and a.eoid = @Eoid) or
          (@GroupID is null and @Eoid is null)
    

    这实际上可以简化为:

    select m.memberid, m.membername, m.groupid, m.eoid
    from membermst m
    where (a.groupid = @GroupID) or
          (@GroupID is null and a.eoid = @Eoid) or
          (@GroupID is null and @Eoid is null)
    

    is not null 比较实际上是多余的。

    【讨论】:

      【解决方案2】:

      你不需要在这里写CASEWHEN,你可以简单地把你的WHERE改成

      where (@GroupID IS NULL OR a.groupid = @GroupID) AND (@Eoid IS NULL OR a.eoid=@Eoid)
      

      如果@GroupID@Eoid 都是NULL,这样您将获得所有记录,如果指定,它将匹配具有各自ID 的记录。

      【讨论】:

      • 哇。这行得通,我谢谢。我从没想过你可以使用 null = null 来生成所有记录。谢谢你的新技术
      【解决方案3】:

      这实际上可以通过以下方式完成:

      select a.memberid, a.membername, a.groupid, a.eoid
          from membermst a 
          where    
          ((@GroupID is null)or((@GroupID is not null)and (a.groupid = @GroupID)))
      

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 2013-03-08
        • 1970-01-01
        • 1970-01-01
        • 2013-09-08
        • 1970-01-01
        • 2020-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多