Overriding rows affected in SQL Server using ExecuteNonQuery?

半城伤御伤魂 提交于 2020-01-04 09:28:41

问题


I have an insert statement that pulls some data into a few table variables and then based on that data does a few inserts into several tables. I only care about the rows that are inserted into the real tables and not the table variables, but ExecuteNonQuery will return the sum of all @@ROWCOUNT's. What I would like to know is there a way to override the rowcount that is returned using ExecuteNonQuery?

I am aware that I can use ExecuteScalar or output variables as an alternative.

Here is an example that boils it down to a simple example:

CREATE TABLE VersionExample ( Version Varchar(255) )  

Declare @RowCountICareAbout int

DECLARE @Example TABLE ( Version Varchar(255) )  

INSERT INTO @Example Select @@VERSION

INSERT INTO VersionExample SELECT Version FROM @Example

SET @RowCountICareAbout = @@ROWCOUNT

--Use @RowCountICareAbout as the rows affected returned to ExecuteNonQuery

回答1:


No idea if this will work, but have you tried SET NOCOUNT ON (and then SET NOCOUNT OFF before your final query)?

Update: this blog post and comments seem to indicate this will indeed work:

http://petesbloggerama.blogspot.com/2006/10/note-to-self-set-nocount-on-not.html




回答2:


No, there is no way to override or alter that behavior in ADO.NET or SQL Server.

The only option you have is to capture the row counts that interest you and put those into a variable and return them.



来源:https://stackoverflow.com/questions/2022515/overriding-rows-affected-in-sql-server-using-executenonquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!