Question

I'm having trouble finding a way around a problem with structuring a table for a unique index.

I have a table where items are reserved and there are several fields that are used to make up

ItemID - INT
Date - DATE
TimeOfDay - INT (morning = 1, afternoon = 2)
ReservationStatus - VARCHAR (expired, cancelled, confirmed, cancelled by admin)

The problem is with the ReservationStatus field. The system should allow for multiple rows that have been cancelled, but only one confirmed or expired (the app changes from confirmed to expired). I'm out of ideas, any help would be appreciated.

Edit:

Full Table Structure

ReservationID - PK Auto-incrementing Integer
SubItemID - INT FK
MemberID - INT FK
Date - DATE
TimeOfDay - INT
ReservationStatus - VARCHAR

SubItemID, Date, TimeOfDay, ReservationStatus need to be unique: More than one member cannot reserve the same SubItem in the afternoon on the same date.

I validate this through my app, however I want to ensure the integrity (in case of programmer error) via the table structure.

Was it helpful?

Solution

To implement this business rule in this table structure with a unique key constraint, you're going to have to do something slightly unnatural.

You could add a column called CancellationCode. Make it an INT. Reserve the value 0 in that column to mean active / expired, and make that the default value. Then, if you cancel a reservation, assign a unique nonzero value to the CancellationCode in that row. You could use your ReservationID value in the row for that, or you could have a Cancellation table with its own unique id.

You can keep your ReservationStatus column so you can tell what's going on with a reservation. But when you look up active / expired reservations, use WHERE CancellationCode = 0, just in case CancellationCode and ReservationStatus get out of sync.

Then make yourself a unique index on (SubItemId, Date, TimeOfDay, CancellationNumber). This will foil any attempts to insert new active reservation rows for the same combinations of SubItemId, Date, TimeOfDay values as existing rows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top