System.Data.Common.DbCommand.ExecuteNonQuery() execute “merge into" returns a negative number

陈啟森 1 Reputation point
2021-05-27T10:17:31.007+00:00

Database: Azure SQL
Programming language: C#.NET

System.Data.Common.DbCommand.ExecuteNonQuery() executes the merge into statement. It is not clear why the negative number is returned. Has anyone encountered a similar problem?
The program has been running for more than half a year and has not had this problem, and it has only recently appeared suddenly.
This phenomenon cannot reappear locally, and sometimes the same sql returns not a negative number, sometimes it returns a negative number, so I have not been able to find the reason.

The structure of the executed merge into statement is as follows:
MERGE
INTO TABLE_A AS A
USING (
SELECT ...
) AS B
ON (
...
) WHEN MATCHED THEN UPDATE
SET
...
WHEN NOT MATCHED THEN
INSERT (
...
)
VALUES (
...
);

Azure SQL Database
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Dan Guzman 9,401 Reputation points
    2021-05-28T11:44:34.33+00:00

    In my experience, System.Data.SqlClient.SqlCommand.ExecuteNonQuery() will return the sum of the rows affected by the batch as long as the session setting is SET NOCOUNT OFF (the default). A negative value, -1, will be returned only when SET NOCOUNT ON is specified. The row count value returned should be the same whether the SqlCommand.ExecuteNonQuery() is invoked directly or via the base type System.Data.Common.DbCommand.ExecuteNonQuery()base type (as in your case).

    Are you reusing the same connection for different queries? If so, perhaps a previous command executed SET NOCOUNT ON; and the setting was still effective when the MERGE statement was executed on the same connection. Check for SET NOCOUNT ON; in other queries that might use the same connection.

    1 person found this answer helpful.

  2. Olaf Helper 47,436 Reputation points
    2021-05-27T10:26:23.13+00:00

    Has anyone encountered a similar problem?

    What for a problem? It's a documented behavior, see DbCommand.ExecuteNonQuery Method
    "For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1 ."
    MERGE is not one of the mentions DDL commands, even because it's a MS SQL Server specifc command, not directly available in other RDBMS, e.g. in Oracle the similar command is UpSert.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.