Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only result of update query

Tags:

c#

sql-server

When I execute an update on my SQL Server database, I get a result of the rows affected by the update AND the affected rows of some triggers.

So for example, an update executed directly on database:

UPDATE: (32 row(s) affected)
Trigger1: (1 row(s) affected)
Trigger2: (2 row(s) affected)
...

Now when I execute _context.Database.ExecuteSqlCommand(query, params) I always get the sum of all those results, in my example the result value is 35.

I only need the result of the UPDATE, in my example 32.

Is there any possibility to ignore the results of the triggers?

like image 757
Obl Tobl Avatar asked Jul 25 '14 12:07

Obl Tobl


People also ask

What is the return value of update query?

"The update() method is applied instantly and returns the number of rows affected by the query." The actual return value depends on the database backend. MySQL, for example, will always return 1 if the query is successful, regardless of the number of affected rows.

Can we use SELECT in update statement?

The subquery defines an internal query that can be used inside a SELECT, INSERT, UPDATE and DELETE statement. It is a straightforward method to update the existing table data from other tables. The above query uses a SELECT statement in the SET clause of the UPDATE statement.

Why SELECT * is not recommended?

Avoid using SELECT * There are many reasons for that recommendation, like: SELECT * Retrieves unnecessary data besides that it may increase the network traffic used for your queries. When you SELECT *, it is possible to retrieve two columns of the same name from two different tables (when using JOINS for example).

What does update statement return in SQL?

Returns values from updated rows, eliminating the need to SELECT the rows afterward. You can retrieve the column values into variables or host variables, or into collections or host arrays.


2 Answers

Put SET NOCOUNT ON on the first line of your triggers.

like image 56
Alireza Avatar answered Oct 14 '22 22:10

Alireza


I think @Alireza's answer makes the most sense if it's possible to change the triggers but if it's not could you change your database call to execute the update statement and return @@ROWCOUNT?

_context.Database.SqlQuery<int>("update xx ...; select @@ROWCOUNT");

I can't find any documentation on MSDN but this question confirms that @@ROWCOUNT is unaffected by triggers.

like image 35
petelids Avatar answered Oct 14 '22 22:10

petelids