So I have this stored procedure to insert a message into my database. I wanted to prevent users from posting duplicate messages within a short period of time, whether on accident or on purpose (either a laggy connection or a spammer).
This is what the insert statement looks like:
IF NOT EXISTS (SELECT * FROM tblMessages WHERE message = @message and ip = @ip and datediff(minute,timestamp, getdate()) < 10)
BEGIN
INSERT INTO tblMessages (ip, message, votes, latitude, longitude, location, timestamp, flags, deleted, username, parentId)
VALUES (@ip, @message, 0, @latitude, @longitude, @location, GETDATE(), 0, 0, @username, @parentId)
END
You can see I check to see if the same user has posted the same message within 10 minutes, and if not, I post it. I still saw one dupe come through yesterday. When I checked the timestamp of both messages in the database, they were exactly the same, down to the second, so I’m guessing when this ‘exists’ check ran on each insert, both came back empty, so they both inserted fine (at basically the same exact time).
What’s a way I can prevent this from happening correctly?
I reckon you need a trigger
A unique constraint/index isn’t clever enough to deal with the 10 minute gap between posts for a given message and ip.
Edit: you need an extra condition to ignore the same row you have just inserted (eg using surrogate key)