日期:2014-05-17  浏览次数:20428 次

多条件查询 SQL 查询的时候应该怎么办!
比如当选着“全部”的时候 sql 中的查询语句 a.GongSiNo = '"&request("gongsi")&"' 不应该有!

现在的语句是这样的!


select a.gongsimc,a.card_kehu_no as kehu_no,a.card_no,a.card_kehu_mc as kehu_mc,a.card_kehu_shouji as kehu_dh,a.che_no,a.card_kind,a.card_enddate,lastdate,datediff(day,isnull(lastdate,getdate()-365),getdate()) days from (select zhifu_card_no,max(lastdate) as lastdate  from (select zhifu_card_no ,xche_jsrq  lastdate from work_pz_sj union select zhifu_card_no,xc_rq lastdate from work_xiche_pz_sj union select zhifu_card_no,xiao_rq lastdate from xiaosh_pz_sj union select card_no as zhifu_card_no,xche_jsrq  lastdate from work_pz_sj union select card_no as zhifu_card_no,xc_rq lastdate from work_xiche_pz_sj union select card_no as zhifu_card_no,xiao_rq lastdate from xiaosh_pz_sj) aa  group by zhifu_card_no) b left join card a  on b.zhifu_card_no=a.card_no  where a.card_no is not null and lastdate>='"&request("txtBeginDate")&"' and lastdate<='"&request("txtEndDate")&"' and a.GongSiNo = '"&request("gongsi")&"' and datediff(day,isnull(lastdate,getdate()-365),getdate())>='"&request("txtDay")&"' and datediff(day,isnull(lastdate,getdate()-365),getdate())<='"&request("txtDay2")&"' ORDER BY lastdate

------解决方案--------------------
后台判断 当全部时 直接SQL
当非全部时 SQL+“and  a.GongSiNo = '"&request("gongsi")&"'”
SQL=


select a.gongsimc,a.card_kehu_no as kehu_no,
a.card_no,a.card_kehu_mc as kehu_mc,
a.card_kehu_shouji as kehu_dh,
a.che_no,
a.card_kind,
a.card_enddate,
lastdate,
datediff(day,isnull(lastdate,getdate()-365),getdate()) days 
from (
select zhifu_card_no,
max(lastdate) as lastdate  
from (
select zhifu_card_no ,
xche_jsrq lastdate 
from work_pz_sj 
union 
select zhifu_card_no,
xc_rq lastdate 
from work_xiche_pz_sj 
union 
select zhifu_card_no,
xiao_rq lastdate 
from xiaosh_pz_sj 
union 
select card_no as zhifu_card_no,
xche_jsrq  lastdate 
from work_pz_sj 
union 
select card_no as zhifu_card_no,
xc_rq lastdate 
from work_xiche_pz_sj 
union 
select card_no as zhifu_card_no,
xiao_rq lastdate 
from xiaosh_pz_sj
) aa  
group by zhifu_card_no
) b 
left join card a  
   on b.zhifu_card_no=a.card_no  
where a.card_no is not null 
and lastdate>='"&request("txtBeginDate")&"' 
and lastdate<='"&request("txtEndDate")&"' 
and datediff(day,isnull(lastdate,getdate()-365),getdate())>='"&request("txtDay")&"' 
and datediff(day,isnull(lastdate,getdate()-365),