Hello again
I can see several ways of doing this without actually resorting to an
extra table.
Option 1
_______
It can be done by creating a trigger on the table, and using an
integrity check in the trigger that checks the two rows against each
other .
Also note that for clarity it is useful to add another field to the
table, res# , a reservation number that is unique to each reservation.
This stops the trigger checking a record against itself
Step 1: Create your table
CREATE TABLE hotel
(res# int AUTO_INCREMENT,
roomno SMALLINT NOT NULL,
arrival DATETIME NOT NULL,
departure DATETIME NOT NULL,
guest char(30),
PRIMARY KEY (roomno,arrival )
);
Step 2: Create your trigger
CREATE TRIGGER no_overlap
ON hotel
FOR INSERT,UPDATE
AS BEGIN
IF EXISTS (SELECT *
FROM hotel y, hotel x
WHERE y.roomno = x.roomno
AND y.departure > x.arrival
AND y.arrival < x.departure
AND y.res# <> x.res#))
ROLLBACK
END
;
Step 3: Try some inserts and updates. When you try to create an
overlapped reservation, youll get a message telling you that you
cant.
Youll find a full, fairly technical, explanation at
NULLS, PROCEDURALITY AND 'NO-OVERLAP' CONSTRAINTS IN SQL
( http://www.pgro.uk7.net/fp2a.htm )
Option 2
_______
It is also possible to do it with a User Defined Function, and youll
find an explanation and example of that at
Function in check constraint (and in Default definition)
http://www.sqlnet.cz/sql_server/tsql/udf_in_check.htm
Option 3
_______
You can create two more fields on your table, check-in date and
check-out date, which are allowed to be NULL and are completed at
actual check-in and check-out eg
CREATE TABLE hotel
(res# int AUTO_INCREMENT,
roomno SMALLINT NOT NULL,
arrival DATETIME NOT NULL,
departure DATETIME NOT NULL,
CHECKIN DATE,
CHECKOUT DATE,
guest char(30),
PRIMARY KEY (roomno,arrival )
CHECK (ARRIVE < DEPART AND CHECKIN <= CHECKOUT)
);
You can see an Example and explanation of this option at the bottom of
"Creating Tables"
(http://developer.mimer.se/documentation/html_82/Mimer_SQL_User_Manual/Defining_Database4.html
)
Willie-ga |