Sql如何根据参数

时间:2017-02-14 12:03:07

标签: sql date if-statement case

抱歉,我不知道怎么把它放在标题中,我在带有2个日期选择器的aspx页面上有这个查询(让我们说数据和数据2)

select utenti.nome as tecnico, Richieste.IDRic as idchia, richieste.descr as rdescr, ISNULL(richieste.assistremota,0) as assremota, Clienti.RagSociale as ragsoc, richieste.descr as descr, richieste.priorita as prior, richieste.tipo as tipo, richieste.rforologio as rforo, ISNULL(statoric.appuntamento,0) as app, ISNULL(statoric.oradalle,0) as dalle, ISNULL(statoric.oraalle,0) as alle, statoric.ID as idstato 
from clienti 
inner join richieste on clienti.idcliente = richieste.rfcliente 
inner join statoric on statoric.rfric = richieste.idric 
inner join stati on stati.idstato = statoric.rfstato 
inner join utenti on utenti.idutente=statoric.rftecnico 
where statoric.attuale = 1 and statoric.rfstato < 14 and statoric.dataass = @data and statoric.rftecnico = 8 order by app desc, oraalle asc, prior desc

我需要更改&#34;定义.dataass = @ data&#34;部分做到这一点(伪代码):

if data 2 is null then 
    "statoric.dataass = @data"
else
    "statoric.dataass between @data and @data2"
end if

我该怎么办?我试过案例,但是我做错了什么......谢谢

2 个答案:

答案 0 :(得分:0)

尝试合并

... statoric.dataass between @data and coalesce(@data2, @data) ...

答案 1 :(得分:0)

这是一种方法:

where statoric.attuale = 1 and
      statoric.rfstato < 14 and
      ( (@data2 is null and statoric.dataass = @data) or
         statoric.dataass between @data and @data2
      ) and
      statoric.rftecnico = 8 

但是,你可能会考虑这个:

where statoric.attuale = 1 and
      statoric.rfstato < 14 and
      statoric.dataass >= @data and
      statoric.dataass <= coalesce(@data2, @data) and
      statoric.rftecnico = 8 

这种方法的优点是它可以利用(attuale, rftecnico, dataass)上的索引。