Difference between Read Committed and Repeatable Read
READ COMMITTED
Specifies that statements cannot read data that has been modified but not committed by other transactions.
This prevents dirty reads.
Data can be changed by other transactions between individual statements within the current transaction, resulting in nonrepeatable reads or phantom data. This option is the SQL Server default
REPEATABLE READ
Specifies that statements cannot read data that has been modified but not committed by other transactions
and that no other transactions can modify data that has been read by the current transaction until the current transaction completes
Example: let us create table Emp_Temp with following records.
EmpId EmpName DeptId
1 Allen 6
2 Defriez 6
3 Sean 6
4 Alex 6
5 Blex 6
-- Drop table if already exists
if exists(SELECT * FROM SYS.OBJECTS WHERE NAME = 'Emp_Temp')
BEGIN
DROP TABLE Emp_Temp
END
--- Create and insert above data.
create table Emp_Temp (EmpId int primary key,EmpName Varchar(100), DeptId int)
insert Emp_Temp values (1,'Allen', 6)
insert Emp_Temp values (2,'Defriez', 6)
insert Emp_Temp values (3,'Sean', 6)
insert Emp_Temp values (4,'Alex', 6)
insert Emp_Temp values (5,'Blex', 6)
READ COMMITTED
-- Now in session 1 Execute Below Statement, this statement will lock 4th row after passing through shared(S) lock till 3rd Row.
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRAN
update Emp_Temp set EmpId = 4 where EmpId = 4
-- Now in same session 1 read/select all rows.
select * from Emp_Temp
-- Now in Session 2(Create by clicking New Query in Query analyzer) update rows in table Emp_Temp
update Emp_Temp set EmpId = 3 where EmpId = 3
Messages
(1 row(s) affected)
-- in case of Read Committed in session 2 transaction completes by updating 1 rows without waiting for session 1 transaction to complete
REPEATABLE READ
-- Now in session 1 Execute Below Statement, this statement will lock 4th row after passing through shared(S) lock till 3rd Row.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRAN
update Emp_Temp set EmpId = 4 where EmpId = 4
-- Now in same session 1 read/select all rows.
select * from Emp_Temp
-- Now in Session 2(Create by clicking New Query in Query analyzer) update rows in table Emp_Temp
update Emp_Temp set EmpId = 3 where EmpId = 3
-- In case Repeatable Read This will keep on executing till session 1 transaction completes
Note: I Created table Emp_Temp with proper columns to further understand "Non Repeatable Reads OR Phantom Reads")