0

I've got this table here with startDate, endDate, startTime and endTime column.

startDate   endDate     startTime  endTime
2020-01-01  2020-01-02  13:00:00   11:00:00
2020-01-14  2020-01-14  08:00:00   16:00:00
2020-02-01  2020-03-01  12:00:00   12:00:00

I've also got this new set of data:

startDate   endDate     startTime  endTime
2020-01-12  2020-01-15  13:00:00   11:00:00
2020-01-29  2020-02-10  08:00:00   16:00:00

How can I check if the new set of data will have any conflicts with the dates and times which are already in the table? And can I also get a list of dates and times from the table?

Update - What I've already tried is to combine startDate and startTime into a new column as startDateTime where it'll hold datetime datatype so I can just use in between statement to check it but I can't seem to combine those two columns together.

1 Answers1

2

Try this option using join. This will return only conflicting rows from the new data set.

WITH your_table(startDate,endDate,startTime,endTime)
AS
(
    SELECT '2020-01-01','2020-01-02','13:00:00','11:00:00' UNION ALL
    SELECT '2020-01-14','2020-01-14','08:00:00','16:00:00' UNION ALL
    SELECT '2020-02-01','2020-03-01','12:00:00','12:00:00'
),
new_data_set(startDate,endDate,startTime,endTime)
AS
(
    SELECT '2020-01-12','2020-01-15','13:00:00','11:00:00' UNION ALL
    SELECT '2020-01-29','2020-02-10','08:00:00','16:00:00'
)

SELECT A.*
FROM new_data_set A
INNER JOIN your_table B 
ON  CAST(A.startDate+' '+A.startTime AS DATETIME)
    BETWEEN CAST(B.startDate+' '+B.startTime AS DATETIME)
    AND CAST(B.endDate+' '+B.endTime AS DATETIME)

    OR  

    CAST(A.endDate+' '+A.endTime AS DATETIME)
    BETWEEN CAST(B.startDate+' '+B.startTime AS DATETIME)
    AND CAST(B.endDate+' '+B.endTime AS DATETIME)


    OR 
    (
        CAST(A.startDate+' '+A.startTime AS DATETIME) <  CAST(B.startDate+' '+B.startTime AS DATETIME)
        AND
        CAST(A.endDate+' '+A.endTime AS DATETIME) >   CAST(B.endDate+' '+B.endTime AS DATETIME)
    )

Output is-

startDate   endDate     startTime   endTime
2020-01-12  2020-01-15  13:00:00    11:00:00
2020-01-29  2020-02-10  08:00:00    16:00:00
mkRabbani
  • 16,295
  • 2
  • 15
  • 24