HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Checking @@ROWCOUNT failing

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
checkingrowcountfailing

Problem

I have a code similar to the one below in one of my SQL procedures,

declare @rowcount int

update table1
set value = @value
where id = @id

select @rowcount = @@ROWCOUNT

 if ( @rowcount = 0 )
 begin
    insert into table1(id, value1,value2...)
    select (@id, @value1, @value2...)
 end


But it fails rarely, like once in a day etc. That means the data exists in the table and @@rowcount is 0 and it tried to insert data and primary key violation happening. Here all values which are inserting ie. id,value1,value2 etc are integers. Any thoughts?

Solution

I'm not sure why you're using a variable, but you need to protect multiple statements with a transaction. What's happening is two users are calling the procedure at the same time, both are getting rowcount = 0, and then they're both trying to insert as a result.

set transaction isolation level serializable;
begin transaction;

update dbo.table1
  set value = @value
  where id = @id;

if (@@ROWCOUNT = 0)
begin
  insert dbo.table1(id, value1,value2...)
    values(@id, @value1, @value2...);
end 

commit transaction;


I blogged about this since writing this answer:

  • Please stop using this UPSERT anti-pattern

Code Snippets

set transaction isolation level serializable;
begin transaction;

update dbo.table1
  set value = @value
  where id = @id;

if (@@ROWCOUNT = 0)
begin
  insert dbo.table1(id, value1,value2...)
    values(@id, @value1, @value2...);
end 

commit transaction;

Context

StackExchange Database Administrators Q#232558, answer score: 15

Revisions (0)

No revisions yet.