如何在 Oracle 中创建动态 where 子句 (PL/SQL)

How to create a dynamic where clause in Oracle (PL/SQL)

我有以下查询:

SELECT *
FROM FOO
WHERE LOCATION = :LOCATION
AND MY_DATE >= TIMESTAMP :BEGIN AND MY_DATE <= TIMESTAMP :END -- option 1 if :BEGIN & :END is not NULL
AND MY_DATE >= TIMESTAMP :BEGIN AND MY_DATE <= sysdate        -- option 2 if :BEGIN is not NULL & :END is NULL
AND MY_DATE <= TIMESTAMP :END                                 -- option 3 if :BEGIN is NULL & :END is not NULL
AND MY_DATE <= sysdate                                        -- option 4 if both :BEGIN & :END is NULL
ORDER BY MY_DATE;

所以这里 :LOCATION 是由用户使用 OCI8 在代码级别提供的。例如:

require 'oci8'
cursor = conn.parse(query)
cursor.bind_param(':LOCATION', 'Chicago', String)

我只想将 1 到 4 中的一个选项作为最终查询的一部分。例如,如果选项 3 为真(:BEGINNULL & :END 不是 NULL),那么最终查询将是:

SELECT *
FROM FOO
WHERE LOCATION = :LOCATION
AND MY_DATE <= TIMESTAMP :END                                 -- option 3 if :BEGIN is not NULL & :END is NULL
ORDER BY MY_DATE;

用户将在何处提供 :END 日期

require 'oci8'
cursor = conn.parse(query)
cursor.bind_param(':LOCATION', 'Chicago', String)
cursor.bind_param(':START', NULL)
cursor.bind_param(':END', '2001-01-22 12:01:00', String)

并会导致:

SELECT *
FROM FOO
WHERE LOCATION = 'chicago'
AND MY_DATE <= TIMESTAMP '2001-01-22 12:01:00'
ORDER BY MY_DATE;

如何编写查询以允许此逻辑?

想知道您是否交换了对选项 2 和 3 的评论?我看到您在使用 :BEGIN 和 :END 时它们为 NULL

AND MY_DATE >= TIMESTAMP :BEGIN AND MY_DATE <= sysdate        -- option 2 if :BEGIN is NULL & :END is not NULL
AND MY_DATE <= TIMESTAMP :END                                 -- option 3 if :BEGIN is not NULL & :END is NULL

我想你可以试试:

SELECT *
FROM FOO
WHERE LOCATION = :LOCATION
and my_date BETWEEN nvl(:BEGIN,'1900-01-01 00:00:00') and nvl(:END,sysdate)

一个选项是使用 CASE :

SELECT *
  FROM FOO
 WHERE LOCATION = :LOCATION
   AND MY_DATE >= CASE WHEN :BEGIN IS NOT NULL THEN :BEGIN
                       ELSE MY_DATE
                  END
   AND MY_DATE <= CASE WHEN :END IS NOT NULL THEN :END
                       ELSE SYSDATE
                  END
 ORDER BY MY_DATE;