Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Microsoft SQL Server: Programming FAQ

Stored Procedures

How Can I Obtain "Rows Affected" by Execution of a Dynamic SQL Statement? by tlbroadbent
Posted: 26 May 01

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.


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.


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.

Back to Microsoft SQL Server: Programming FAQ Index
Back to Microsoft SQL Server: Programming Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close