SQL 具有单一日期和日期范围的条件 where 子句

SQL conditional where clause with single date and date range

使用 Sybase。

我有一个接受多个参数的存储过程。

@param1 和@date1 总是有值,但@param2、@param3 和@date2 是可选的。

我写过这样的东西。

(@param1, @param2, @param2, @date1, @date2)

SELECT * FROM table
WHERE col1 = @param1
AND col2 = COALESCE(NULLIF(@param2,''), col2)
AND col3 = COALESCE(NULLIF(@param3,''), col3)
AND
IF(@date2 is empty)
  col4 = @date1
ELSE
  col4 IS BETWEEN @date1 AND @date2

寻求有关编写最后一部分的帮助。如果有日期条件。

if 不属于那里。而且不需要:

SELECT *
FROM table
WHERE col1 = @param1 AND
     col2 = COALESCE(NULLIF(@param2,''), col2) AND
     col3 = COALESCE(NULLIF(@param3,''), col3) AND
     ( (@date2 IS NULL AND col4 = @date1) OR
       col4 IS BETWEEN @date1 AND @date2
     )

最优雅的方式是将最后一部分写成:

AND col4 between @date1 and coalesce(@date2, @date1)

这样,如果@date2 为 null,条件将像这样工作:

AND col4 between @date1 and @date1

等于:

AND col4 >= @date1 and col4 <= @date1

等于:

AND col4 = @date1