代码之家  ›  专栏  ›  技术社区  ›  rs.

是否可以将空值传递给SQL参数以查询全部?

  •  1
  • rs.  · 技术社区  · 16 年前

    我有如下疑问

    select * from table where col1 = @param1 and col2 = @parm2
    

    另一个

    select * from table where col1 = @param1
    

    是否可以基于传递的参数在同一查询中执行两个操作?如果为空,则查询全部或当参数具有值时选择它们。

    我的查询非常大,我必须为每个创建两个版本的SP,我在想,我可以避免创建两个版本吗?

    6 回复  |  直到 16 年前
        1
  •  2
  •   Philip Kelley    16 年前
    SELECT * from table where col1 = @param1 and col2 = isnull(@parm2, col2)
    

    应该做你想做的。

        2
  •  1
  •   Locksfree    16 年前

    好吧,你可以试试这个,但我不认为它会有很好的表现:

    SELECT * FROM tab WHERE col1 = @param1 AND col2 = ISNULL(@parm2, col2)
    
        3
  •  1
  •   Paddy    16 年前

    您可以尝试如下操作:

        select * from table where coalesce(@param1, col1) = col1 
    and coalesce(@param2, col2) = col2
    
        4
  •  1
  •   Cade Roux    16 年前

    这里关于使用coalesce或isnull的所有建议 有效地做到这一点:

    select *
    from table
    where (@param1 IS NULL OR col1 = @param1)
        and (@parm2 IS NULL OR col2 = @parm2)
    

    但是 您可能需要注意参数嗅探。SQL Server 2005没有针对未知的优化功能-可以将参数屏蔽为sp中的局部变量,以帮助避免这种情况发生,或者使用重新编译选项。

        5
  •  0
  •   Ray    16 年前

    这个怎么样?

    select *
      from table
      where where (col1 = @param1 and col2 = @parm2)
      or (col1 = @param1 and parm2 is null)
    
        6
  •  0
  •   Asad    16 年前

    如果使用存储过程!

    IF Boolean_expression 
         { sql_statement | statement_block } 
    [ ELSE 
         { sql_statement | statement_block } ] 
    

    在你的场景中。类似的东西

    if (@param1 = null)
    Begin
     select * from table where col2 = @parm2
    ( 
    End
    
    else if (@param1 = 'something' )
    Begin
    (
     select * from table where col1 = @param1
    End
    

    参考文献: http://msdn.microsoft.com/en-us/library/ms182717.aspx