0

Currently I am using the overlaps operator so that users can't insert dates that overlap. I created this function:

    CREATE OR REPLACE FUNCTION overlap(docent_medewerkerscode1 CHARACTER(7),  
lokaal1 TEXT, groep_groepsnaam1 TEXT, startdatum1 timestamp, einddatum1 
timestamp)

RETURNS TEXT AS $$
DECLARE
    resultaat TEXT;
    rec rooster%rowtype;
BEGIN 
    FOR rec IN SELECT groep_groepsnaam = groep_groepsnaam1 OR lokaal =      
lokaal1 OR docent_medewerkerscode = docent_medewerkerscode1 FROM rooster 
  LOOP
        IF(startdatum1, einddatum1) OVERLAPS (startdatum, einddatum) FROM  
rooster THEN
           --IF startdatum1 BETWEEN startdatum AND einddatum AND einddatum1 BETWEEN startdatum AND einddatum FROM rooster THEN
            resultaat = 'tijd overlapt';
            RAISE 'Niet mogelijk tijd komt overeen met ingeplande tijd';
        END IF;
  END LOOP;

RETURN resultaat;
END;
$$ LANGUAGE plpgsql;

The problem is that the overlap doesn't work on multiples rows.

(ERROR: query "SELECT (startdatum1, einddatum1) OVERLAPS (startdatum, einddatum) FROM rooster" returned more than one row)

I am looking for a way that let's the overlap check each row from the select query. Any of you guys that have an idea of what I can do?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Falio
  • 3
  • 2

1 Answers1

0

The immediate cause for the error message is that the plpgsql IF statement expects a single boolean expression, while your code returns a whole set of boolean expressions.

IF(startdatum1, einddatum1) OVERLAPS (startdatum, einddatum) FROM  
rooster THEN

is an ugly short form of:

IF (SELECT(startdatum1, einddatum1) OVERLAPS (startdatum, einddatum)
    FROM  rooster) THEN

and simply invalid this way. You would have to agggregate or use EXISTS:

IF EXISTS (
   SELECT 1 FROM  rooster r
   WHERE  (startdatum1, einddatum1) OVERLAPS (r.startdatum, r.einddatum)
   ) THEN ...

More importantly, an exclusion constraint is almost certainly the better solution for your problem (requires Postgres 9.0+):

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228