【问题标题】:SQL Server, Filter by using selective columnsSQL Server,使用选择性列过滤
【发布时间】:2015-11-14 13:49:53
【问题描述】:

看起来很简单,但我需要这个。我有一个表 tbl(col1,col2,col3)。我想以一种方式在过程中搜索表,就像我只为 col1 传递值时,查询应该只考虑 where 子句中 col1 的值。同样,当我为 col1 和 col2 传递值时,它应该只考虑 where 子句中的这两列并忽略 col3。 我只想使用一个选择查询,例如

'select * from tbl where col1=@col1 and col2=@col2 and col3=@col3'

我原来的过程是:

create proc GetProdData
@source nvarchar(20),
@subsource nvarchar(20)
as
begin
select * From ProductionData 
where Source=@source and SubSource=@subsource
end

【问题讨论】:

    标签: sql sql-server sql-server-2008 sqlite


    【解决方案1】:

    如果你有索引,更有效的方法是生成动态 SQL。

    否则:

    where (col1 = @col1 or @col1 is null) and
          (col2 = @col2 or @col2 is null) and
          (col3 = @col3 or @col3 is null)
    

    【讨论】:

    • @IkramKhan - 显示您的过程定义。只要您没有将这些参数设置为 null 以外的其他值,它应该可以正常工作。
    • 我已经编辑了问题并发布了原始过程。 @马丁史密斯
    • thnku... 经过简单的修改,它现在可以工作了 :)
    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 2017-04-15
    • 2014-05-14
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    相关资源
    最近更新 更多