【问题标题】:Sql where clauseSql where 子句
【发布时间】:2011-11-08 22:07:11
【问题描述】:

我有一个存储过程,我在其中传递要在 where 子句中的 select 语句中使用的值。

如果我传递的值为 NULL,我不希望它成为使用它的 where 子句部分的一部分。在下面的示例中,variable2 是我传递给存储过程并在 sql 语句中使用的变量,但如果 @variable2 为 NULL,我不想在 where 子句中使用 variable2= @val1。示例:

select Field1, Field2 from tbl1
where variable2= @val1
and ID = 'test'

【问题讨论】:

    标签: sql where


    【解决方案1】:

    试试:

    where (@val1 is null or variable2 = @val1)
    and ID = 'test'
    

    【讨论】:

      【解决方案2】:
      select Field1, Field2 from tbl1 
      where (variable2= @val1 or @val1 is null)
      and ID = 'test' 
      

      【讨论】:

        【解决方案3】:

        怎么样:

        select Field1, Field2 from tbl1
        where (@val1 IS NULL or variable2 = @val1)
        and ID = 'test'
        

        【讨论】:

          【解决方案4】:

          您的WHERE 子句应该在左侧有列,这可能是这种情况,但您将其称为variable2。给定特定参数,这将起作用:

          select Field1, Field2
          from tbl1
          where yourColumn = 
          case
              when @param1 is null
              then @param2
          end
          

          我使用了通用字段名称和参数名称,但您应该明白了。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-10-30
            • 2023-03-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-04-17
            • 2022-01-20
            相关资源
            最近更新 更多