Isaac Pounder
Isaac Pounder

Reputation: 187

How to get affected records using ExecuteNonQuery when multiple insert statements are used in C# for SQL

I am running an insert query from c# using:

string affectedRows = myCommand.ExecuteNonQuery().ToString();

However the query that I am running does two things. It first inserts stuff into a temp table, and then inserts stuff into the real-table.

Eg:

declare @t table (a int)
insert into @t 
values(1)

insert into MyTable
select * from @t

Since it does two inserts, my affectedrows will be 2. The question is how to i get either the last result of the insert, or perhaps an array/list of results?

Dividing by 2 won't help me, as there maybe multiple queries, etc and it won't always be 2. the above is just an example. Thanks

Upvotes: 1

Views: 1301

Answers (1)

Gustavo F
Gustavo F

Reputation: 2206

Just change the SET NOCOUNT statement to view the lines that really matter:

example:

set nocount off

declare @t table (a int)
insert into @t 
values(1)

set nocount on

declare @MyTable table (b int)

insert into @MyTable
select * from @t

See the Messages tab in SSMS.

Upvotes: 4

Related Questions