Skip to content
Advertisement

@@ROWCOUNT shows as 0 when deleting using dynamic query SQL

I am facing a trouble when using dynamic query and when trying to get the number of deleted records using @@ROWCOUNT

Here is my QUery

Here after the dyanimic delete query (inside my cursor) I am trying to store the number of deleted records into another table using @@ROWCOUNT. But it shows as 0.

I didnt understand what I did wrong.

My SQL version is 2012

Advertisement

Answer

@@ROWCOUNT is working correctly. From the documentation:

Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.

The prior statement to the statement you use @@ROWCOUNT in is print @query and that returns no rows, and hence @@ROWCOUNT returns 0.

To fix this I would suggest PRINTing your dynamic statement first. Also you need to fix your dynamic statement so it isn’t open to injection. Don’t use the syntax EXEC (@SQL), use a parametrised call to sys.sp_executesql and ensure you properly delimit identify your dynamic object with QUOTENAME:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement