SQL Server,使用选择性列进行筛选

时间:2015-11-14 13:49:53

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

看起来很简单,但我需要这个。我有一个表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

1 个答案:

答案 0 :(得分:1)

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

否则:

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