条件存储过程内的WHERE子句

时间:2014-12-01 17:54:43

标签: sql sql-server tsql stored-procedures where-clause

我正在使用存储过程,我想根据几个参数的值添加或删除WHERE子句。

这是我到目前为止所得到的:

WHERE 
   t.iDdPais = @iIdPais
   AND t.iIdRegion = @iIdRegion
   AND t.dtFecha BETWEEN @dtStart AND @dtEnd

但是,如果@iIdPais为0(表示ALL),我需要从WHERE语句中删除该子句,同样适用于@iIdRegion。

2 个答案:

答案 0 :(得分:4)

你只需要使用普通的布尔逻辑:

WHERE 
  (@iIdPaid = 0 OR t.iDdPais = @iIdPais)
  AND (@iIdRegion=0 OR t.iIdRegion = @iIdRegion)
  AND t.dtFecha BETWEEN @dtStart AND @dtEnd

答案 1 :(得分:4)

将整个SELECT放在IF子句中。

IF(@ildPais =0 AND @ildRegion =0)
SELECT <THE DATASET> FROM THE TABLE
WHERE 
   t.iDdPais = @iIdPais
   AND t.iIdRegion = @iIdRegion
   AND t.dtFecha BETWEEN @dtStart AND @dtEnd

ELSE 
SELECT <THE DATASET> FROM THE TABLE
--no where clause