在 Oracle Sql 中查找两个日期列之间的记录

Finding records between two Dates column in Oracle Sql

我有一个 table,它有两列 Start_Date 和 End_Date。我想在此 table 中插入一条新记录,但在插入之前,需要检查在开始日期和结束日期范围内是否有记录。

 ID    Start_Date      End_Date
 1     01/01/2022      01/15/2022
 2     01/16/2022      01/20/2022
 3     02/01/2022      02/28/2022
 4     01/27/2022      01/29/2022

我想用 Say 插入一条新记录

  Start_Date as 01/18/2022 and end date as 03/31/2022.

是否可以使用 sql 检查该日期范围内的记录,或者我们需要编写 plsql

您可以检查是否存在重叠范围,如果存在则避免插入:

INSERT INTO yourTable (Start_Date, End_Date)
SELECT date '2022-01-18', date '2022-03-31'
WHERE NOT EXISTS (
    SELECT 1
    FROM yourTable
    WHERE date '2022-01-18' < End_Date AND date '2022-03-31' > Start_Date
);