I have a table where new data gets filled each time a user clicks an option on my website. I created this table via Management Studio and I want to clarify that neither I am creating this table each time via stored procedure nor I am using any type of in-memory temporary tables.
Whenever user clicks an option on my website, old records from this table are deleted first and new records are filled. I am worried about the concurrency issue that may arise when many users click the same option from my website. I am not aware of how SQL Server is going to handle multiple delete and inserts into this table.
I read somewhere that SQL Server Services automatically handle this issue with a separate session-wise copy of the table for each session.
Is there a need to add SPID in my table or it is automatically taken care of? Do I need to change the isolation level from Read Committed to Serializable?
The general answer to the question you’re asking is that yes you will need to have some sort of session identifier column in your table and pass the value in it for each user/session along to all stored procedures and/or SQL statements that operate on that table.
The alternative is that yes, you could set the isolation level to Serializable and have your users queue up one behind the other waiting until everyone in front of them is done and let SQL Server handle it, but that’s almost never what you want to do.
So roughly, for the first option, you’ll end up with something like :
YourTable
So a User logs in/starts a Session on your site. You use their ID or generate a SessionID for them and pass it to
you get the idea.
Basically as long as every SQL statement you use to touch the table has as part of the WHERE clause or insert statement:
then you’re probably well on your way to having a table that can be safe shared by several users at the same time as you described.
For the second option, please
read this so you realize what you’re getting yourself into. 🙂
Then put code like this
Just in case you don’t read the link:
SERIALIZABLE
Specifies the following:
This blocks other transactions from updating or inserting any rows that would qualify for any of the statements executed by the current transaction. This means that if any of the statements in a transaction are executed a second time, they will read the same set of rows. The range locks are held until the transaction completes. This is the most restrictive of the isolation levels because it locks entire ranges of keys and holds the locks until the transaction completes. Because concurrency is lower, use this option only when necessary. This option has the same effect as setting HOLDLOCK on all tables in all SELECT statements in a transaction.