我正在努力寻找更好的方法来完成我正在尝试做的事情。
我有两个数据库表(Booking 和 TimeSlots)
Booking 是一个约会列表,TimeSlots 是一个时间段列表。
我想要做的是当某些东西被插入到 Booking 中时,获取第一行未标记为已使用的 TimeSlot(没有人应该具有相同的 TimeSlot),然后将 TimeSlot 标记为已使用,因此它不再是第一行未标记为已拍摄
我最初有这个:
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)
但是,如果两个插入是在完全相同的时间进行的,则问题在于它们都获得相同的日期和时间段。
所以我想出了这个:
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
这还不错,我获得了插入的 ID,根据 slotOrder 和插入的 ID 获取时间段,然后更新时间段,并使用日期和时间段更新约会。
与此有关的问题,我的数据库并不总是以 1 开头,我无法获取第一个未标记为已占用的时间段,如果删除了时间段,则插入约会表将没有时间段,我不不喜欢根据最近插入的 ID 从另一个表中获取另一个值的想法
在我没有根据 ID 获得一行的情况下,是否有关于如何改进这一点的任何建议,理想情况下,我希望根据行顺序而不是 ID 获得它
使用事务获取时间段值,然后更新它以将其设置为已使用。这将阻止其他用户获得相同的时间段。
begin transaction
SELECT TOP 1 @DateSlot = dateSlot, @TimeSlot = timeSlot FROM TimeSlots WHERE taken = 0
UPDATE TimeSlots SET taken = 1 WHERE dateSlot = @DateSlot AND timeSlot = @TimeSlot
commit transaction
INSERT INTO Booking (email, dateSlot, timeSlot, startTime, dateCreated, createdBy, dateModified, modifiedBy, isWaitList) VALUES (@Email, @DateSlot, @TimeSlot, @StartTime, GETDATE(), @Email, GETDATE(), @Email, @IsWaitListed)
现在没有两个用户会得到相同的时间段,即使他们同时提交请求。也适用于数十个用户。当事务未提交时,用户将被阻止。而且由于事务中只有 2 行 SQL,因此速度会非常快。我怀疑用户甚至会注意到(只要select top 1 ...
查询快速返回——如果没有,您将需要对该表进行索引,以便它立即返回)。
另外,order by
您的select top 1 ...
查询是否需要一个子句以确保它始终以相同的顺序返回可用的时间段?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句