日期:2014-05-18  浏览次数:20620 次

SQL多条件查询
各位高手:
  SQL 中怎么进行多条件查询呀?具体如下!
我现在有四个查询条件
 A , B ,C,D

查询:
 select * from table where column.a=a and column.b=b and column.c=c and column.d=d
如果A.B.C.D都有值时查出来的结果是对的, 可以当有其中的一个没有结果查询出来就对
我现在都是用IF 判断四个条件有没有值过在做过滤查询, 好麻烦如:
if a='' and b='' and c='' and d<>'' --当A=''b=''c=''时不做条件过滤
begin
 select * from table where column.d=d
end
像这样要判断N次,而且判断漏一种有时候还会报错,有没有那位高手有好办法呀

------解决方案--------------------
用动态语句吧
------解决方案--------------------
SQL code
select * 
from table 
where a=isnull(@a,a) and b=isnull(@b,b) and c=isnull(@c,c) and d=isnull(@d,d)

------解决方案--------------------
SQL code
select * 
from table 
where column.a=case when isnull(a,'')!='' then a else column.a end
and column.b=case when isnull(b,'')!='' then a else column.b end
and column.c=case when isnull(c,'')!='' then a else column.c end
and column.d=case when isnull(d,'')!='' then a else column.d end

------解决方案--------------------
探讨
SQL codeselect*fromtablewhere a=isnull(@a,a)and b=isnull(@b,b)and c=isnull(@c,c)and d=isnull(@d,d)

------解决方案--------------------
探讨
SQL codeselect*fromtablewhere a=isnull(@a,a)and b=isnull(@b,b)and c=isnull(@c,c)and d=isnull(@d,d)

------解决方案--------------------
svrnfd根据需要动态构造条件语句。
------解决方案--------------------
SQL code

create proc w_wsp
@a varchar(50)=null,
@b varchar(50)=null,
@c varchar(50)=null,
@d varchar(50)=null
as
    select * from [table] where a=isnull(@a,a) and b=isnull(@b,b) and c=isnull(@c,c) and d=isnull(@d,d)
go

--调用,只有a有值时
exec w_wsp @a='aa'