Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this statement do @@RowCount > 0

Taken from the book : "Julia Lerman - Programming Entity Framework "

when creating a new entity in EF :

   var contact = Contact.CreateContact(0, "Camey", "Combs", DateTime.Now, DateTime.Now);
   context.Contacts.AddObject(contact);
   context.SaveChanges(); 

The generated sql :

   exec sp_executesql N'insert [dbo].[Contact]([FirstName], [LastName], [Title],
   [AddDate], [ModifiedDate])
   values (@0, @1, null, @2, @3)
   select [ContactID]
   from [dbo].[Contact]
   where @@ROWCOUNT > 0 and [ContactID] = scope_identity()',
   N'@0 nvarchar(50),@1 nvarchar(50),@2 datetime2(7),@3 datetime2(7)',
   @0=N'Camey',@1=N'Combs',@2='2009-08-30 09:27:31.7449098',
   @3='2009-11-30 09:27:31.7449098'

What is @@RowCount > 0 used for in the where clause ?

I'm not sure of what it does according to msdn it returns the number of affected rows , so as i understand it , this is just a way the verify that the Contact record was added they could of also have written @@ROWCOUNT = 1

is this correct ?

like image 411
eran otzap Avatar asked Dec 20 '13 15:12

eran otzap


2 Answers

@@Rowcount is a special variable. It will always hold the number of records changed or returned by the last statement. In this case, the last statement was the insert. By using @@Rowcount > 0 in the where clause, you make sure the select only matches any records if the insert statement succeeded.

If they had used @@Rowcount > 1 instead, that statement would never be true. That insert statement will only insert 1 row. 1 is not > 1.

like image 127
Joel Coehoorn Avatar answered Sep 27 '22 23:09

Joel Coehoorn


@@Rowcount = the number of rows affected by the last statement

In your case, this checks that the insert did not encounter an error such as a row with the same primary key

like image 40
JunkBox Avatar answered Sep 27 '22 22:09

JunkBox