Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How Can I Obtain "Rows Affected" by Execution of a Dynamic SQL Statement?

Stored Procedures

How Can I Obtain "Rows Affected" by Execution of a Dynamic SQL Statement?

by  tlbroadbent  Posted    (Edited  )
When a SQL statement is executed using the Execute command, it is not possible to obtain the rows affected count. At least I've not been able to find a way to obtain this value.

Example:

declare @sql nvarchar(1024), @rc int

set @sql="Update tbl Set ColA='Testing' where ID between 101 and 104"

Execute(@sql) /* or Exec(@sql) */
set @rc=@@rowcount


After executing this segment of T-SQL code, @rc does not contain the actual rows affected.

SQL Server 7 and 2000 provide a system-stored procedure named sp_executesql. SQL Books Online say this about sp_executesql:

"Executes a Transact-SQL statement or batch that can be reused many times, or that has been built dynamically. The Transact-SQL statement or batch can contain embedded parameters." (emphasis added)

sp_executesql has several advantages over the Execute command. One of the advantages is being able to determine the number of rows affected by the query.

Example:

declare @sql nvarchar(1024), @rc int

set @sql="Update tbl Set ColA='Testing' where ID between 101 and 104"

exec sp_executesql @sql
set @rc=@@rowcount


The value of @rc upon completion of this segment of T-SQL code will be the actual number of rows affected.

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top