I want to guarantee that a token is assigned to an order. All available tokens are inside the Token table and each token can ONLY be assigned to 1 order. Here is the sql I came up with:
SET XACT_ABORT ON;
BEGIN TRANSACTION
-- Reserve token.
SELECT @token = token, @tokenId = id FROM Tokens WITH (UPDLOCK) WHERE taken = 0;
-- Take token.
UPDATE Tokens SET taken = 1 WHERE id = @tokenId;
-- Assign token to the order.
UPDATE Orders SET token = @token WHERE ID = @orderId;
COMMIT TRANSACTION
Can the above code guarantee that
- if there is an available token inside Tokens table, then it will be selected and assigned to an order.
- each token will not be assigned to more than 1 order.
- Statement will never fail in error.
Do you see any other potential problems with this statement?