2

使用 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

在编写最后一部分时寻求帮助。如果条件与日期。

4

2 回答 2

1

最优雅的方法是将最后一部分写为:

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
于 2018-06-26T20:46:16.847 回答
1

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
     )
于 2018-06-26T20:34:41.943 回答