I am trying to find a better way to accomplish what I am trying to do.
I have two database tables (Booking and TimeSlots)
Booking is a list of appointments, TimeSlots is a list of time slots.
What I am trying to do is when something gets inserted into Booking, get the first row of TimeSlot that is not marked as taken (no one should have the same TimeSlot) and then mark the TimeSlot as taken, so its not longer the first row that is not marked as taken
I originally had this:
SELECT TOP 1 @DateSlot = dateSlot, @TimeSlot = timeSlot FROM TimeSlots WHERE taken = 0
UPDATE TimeSlots SET taken = 1 WHERE dateSlot = @DateSlot AND timeSlot = @TimeSlot
INSERT INTO Booking (email, dateSlot, timeSlot, startTime, dateCreated, createdBy, dateModified, modifiedBy, isWaitList) VALUES (@Email, @DateSlot, @TimeSlot, @StartTime, GETDATE(), @Email, GETDATE(), @Email, @IsWaitListed)
But the problem with this if two inserts were made at the exact same time, they both with get the same date and time slot.
So I came up with this:
SELECT @AppointmentAccepted = 1
SELECT @IsWaitListed = 0
//Insert Into the database
INSERT INTO Booking (email, dateSlot, timeSlot, startTime, dateCreated, createdBy, dateModified, modifiedBy, isWaitList) VALUES (@Email, ‘’, '', @StartTime, GETDATE(), @Email, GETDATE(), @Email, @IsWaitListed)
//Get the ID of the new insert
SET @TableA_PK=SCOPE_IDENTITY()
//Get Time Slot Where slotOrder = New Insert ID
SELECT @DateSlot = dateSlot, @TimeSlot = timeSlot FROM TimeSlots WHERE slotOrder = @TableA_PK
//Update The database with Date and Time Slot
UPDATE Booking SET dateSlot = @DateSlot, timeSlot = @TimeSlot WHERE id = @TableA_PK
//Update Time Slot as taken
UPDATE TimeSlots SET taken = 1 WHERE slotOrder = @TableA_PK
Which is not bad, I get the ID for the insert grab the time slot based on slotOrder and ID from the insert, then update the time slot as taken and update the appointment with date and time slot.
The issue with this, my database does not always start with 1 and I can’t grab the first Timeslot that is not marked as taken and if a TimeSlot gets deleted, an insert into the appointment table will not have a Time Slot, I don’t like the idea of grabbing another value from another table based off the recent inserted ID
Are there any suggestions on how to improve this where I am not getting a row based off ID, Ideally I would love to get it based off Row Order instead of IDs