Tuesday, September 25, 2012

SET NOCOUNT Usage


SET NOCOUNT ON, in SQLSERVER, is used to stop the message that shows the count of the number of rows affected by the SQL statement written in the stored procedure or directly SQL Statement. You can view this message in the Management Studio in the Message tab of the result pan. 

When NOCOUNT is ON - the number of affected rows will not be returned 
 When NOCOUNT is OFF - the number of affected rows will be returned   

Triggers also need it, as its useful, If we don't turned on NOCOUNT, their performance can be drastically affected . Take, for example, INSERT triggers that are fired repeatedly, especially when using INSERT INTO statements for massive insert operations. In such cases where the trigger is fired over and over again during the course of the statement, the trigger will issue DONE_IN_PROC messages for each INSERT action, which can slow things down drastically. 

This slow down is especially pronounced if the trigger is being fired as the result of a scheduled SQL Server Agent job. SQL Server Agent automatically imposes a delay after each DONE_IN_PROC signal to avoid server congestion. If you try running the same set of commands through the Query Analyzer, it will execute much faster since no such delays are imposed. If you run such a query through Query Analyzer and see multiple "n rows affected" statements, there's a good chance the query is iterating repeatedly and re-firing the trigger many more times than it really needs to. To turn off DONE_IN_PROC messages, use the SET NOCOUNT ON command at the start of a trigger statement. 

 Microsoft actually encourages the use of SET NOCOUNT ON in Stored Procedures. 
 There is another thing @@ROWCOUNT, which is relevant to this. It is used to get the number of rows affected. Note that either the SET NONCOUNT is ON or OFF, @@ROWCOUNT is always updated with the number of rows affected.

 I hope this post help everyone in understanding the usage of SET NOCOUNT. Thank You.


No comments:

Post a Comment

Earn Money ! Affiliate Program
Open Directory Project at dmoz.org