我正在使用存储过程,我想根据几个参数的值添加或删除WHERE子句。
这是我到目前为止所得到的:
WHERE
t.iDdPais = @iIdPais
AND t.iIdRegion = @iIdRegion
AND t.dtFecha BETWEEN @dtStart AND @dtEnd
但是,如果@iIdPais为0(表示ALL),我需要从WHERE语句中删除该子句,同样适用于@iIdRegion。
答案 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