简体   繁体   中英

C# & SQL Server : ExecuteNonQuery returning -1, when UPDATE works?

Apologies if this has been asked before. I have searched for an hour and not found the exact problem I am having.

I am using SMO to run some queries against SQL Server, because I have read this can handle GO statements, as opposed to System.Data.SqlClient .

I am running this query:

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO  

UPDATE Program
SET ENABLED = '1'
WHERE Program_ID = '64' AND Program_Name = 'DoesSomething' 

I am capturing the "rows affected" by:

int numberOfRows = db.ConnectionContext.ExecuteNonQuery(s.Query);

The problem I am having is that this returns a value of -1 every time. I am checking the database behind the scenes and it DOES update the value every time, and when I manually run the query in SSMS, I receive the (1 row affected) confirmation.

After reading some other posts I have come to think the problem may be in the first four lines of this query. I removed the GO statements, and the query returned with a value of 1 instead of -1.

Most queries/scripts my group writes has GO , SET ANSI_NULLS ON , and SET QUOTED_IDENTIFIER ON pretty much as standard so its everywhere (another problem for another day- I'm aware it is excessive/irrelevant in this case). Is this affecting my row count somehow? If so can you provide some direction for a workaround or perhaps another route to get this result?

And yes... I am aware ExecuteNonQuery should return the number of rows affected. I just need to know why it is not returning what I think it should (in this case 1).

GO is a the batch seaparator used by SQLCMD, OSQL and other tools. Since SMO's ServerConnection.ExecuteNonQuery happens to recognize the SQLCMD commands, it handles the batch separator for you and executes every batch you issue in your text. The 'return' value of a series is not a clear command, since each batch may have its own return (not to mention that every batch may contain multiple statements). So I would take that 'return' value with a grain of salt. If you want to confirm the number of rows updated, use an OUTPUT clause in the UPDATE and have a result set, or assign @@ROWCOUNT to an output variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM