I am doing a project in SQL Oracle and have found a problem, as far as I am quite new to SQL.
I have a system that administrates booked rooms, in a table called bookings. Some of the attributes are:
- room_id
- arrival_date
- nights_nr
- booking_id (which is the PK).
I have a UNIQUE(room_id, arrival_date) constraint.
To have a coherent DB I would need to check, for every inserted or updated row, whether any of the intended-to-book days for that room are already booked. This being a constraint based on the table's values, I would need a select so I cannot perform this in a CHECK (or at least I haven't figured out another possibility).
I am trying to do this with a trigger, but this is my first contact with triggers.
What I thought was to have a select in a when and to verify if, for another booking_id and the same room_id I am currently intending to update, the range of days I am intending to book intersects with the range booked.
Due to lack of knowledge I have written something like this:
CREATE OR REPLACE TRIGGER validate_free_room
BEFORE INSERT OR UPDATE OF arrival_date, night_nr ON bookings
FOR each row
DECLARE a char(8)
DECLARE b char(3)
SET a=booking_id
SET b=room_id
WHEN EXISTS (
SELECT booking_id
FROM bookings r
WHERE
(r.booking_id!=a
AND
((arrival_date BETWEEN r.arrival_date AND r.arrival_date + nights_nr)
OR
(arrival_date + nights_nr BETWEEN r.arrival_date AND r.arrival_date + r.nights_nr)
)
AND
b=r.room_id
)
)
BEGIN
RAISE_APPLICATION_ERROR (-20107,'Room already booked')
end;
I have just found out that I cannot perform selects in a table that is being modified with a "for each row".
Do you have any ideas how I could do this in a correct way? (I know the precedent lines are a complete disaster).
I am using Oracle Application Express, which gave me the following error suggestions:
ORA-24344: success with compilation error
ORA-06512: at "SYS.WWV_DBMS_SQL_APEX_190200", line 592
ORA-06512: at "SYS.DBMS_SYS_SQL", line 1658
ORA-06512: at "SYS.WWV_DBMS_SQL_APEX_190200", line 578
ORA-06512: at "APEX_190200.WWV_FLOW_DYNAMIC_EXEC", line 2057
3. for each row
4. declare a char(8)
5. declare b char(3)
6. set a=id_rezerva
7. set b=id_camera
and
Error computing plan for statement.
ORA-00900: invalid SQL statement