6

These answers (1, 2), using code from this article, recommend using the statement SET NOCOUNT ON as a temporary placeholder/dummy body for a stored procedure whose body will be overwritten shortly.

Neither those answers nor that article specify why SET NOCOUNT ON was chosen as the value for the temporary stored procedure body.

My question: Why is SET NOCOUNT ON a good choice for a temporary stored procedure body which will (if all goes well) be overwritten in a subsequent operation? Is there a better alternative?

Some criteria that come to mind for what might constitute a good temporary / placeholder stored procedure body:

  • Fails in an obvious way at runtime if for some reason the subsequent ALTER of the stored procedure doesn't happen as planned;
  • Is easy to understand by future developers maintaining the stored procedure;
  • Doesn't add any significant overhead.
Community
  • 1
  • 1
Jon Schneider
  • 25,758
  • 23
  • 142
  • 170

2 Answers2

7

To better meet the "criteria" from my question, I've landed on replacing SET NOCOUNT ON with a RAISERROR statement.

My code to ensure a stored procedure exists before running an ALTER PROCEDURE on it ends up looking like:

-- Create the sproc with a temporary body if it doesn't exist yet. 
-- We'll set the real body in the ALTER PROCEDURE statement below.
IF NOT EXISTS (
  SELECT * FROM sys.objects
    WHERE name = 'MyStoredProcedureNameHere'
    AND type = 'P'
) BEGIN
  EXEC ('CREATE PROCEDURE MyStoredProcedureNameHere AS
    RAISERROR (''The ALTER PROCEDURE to set the body for MyStoredProcedureNameHere did not run as it should have!'', 16, 1);');
END
GO

ALTER PROCEDURE MyStoredProcedureNameHere AS ...

So, if the ALTER PROCEDURE somehow fails to run, then if my stored procedure gets executed, it'll raise an error instead of silently doing nothing (as would be the case with a body consisting only of SET NOCOUNT ON).

Credit for this approach: http://www.codeofhonor.com/blog/a-better-way-to-update-sql-stored-procedures

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
5

This is probably because including SET NOCOUNT ON; is considered good practice. It is included in the template SP, generated by SSMS. From the MSDN article on NOCOUNT:

NOCOUNT ON prevents the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. For stored procedures that contain several statements that do not return much actual data, or for procedures that contain Transact-SQL loops, setting SET NOCOUNT to ON can provide a significant performance boost, because network traffic is greatly reduced.

The idea is NOCOUNT is first used a placeholder. Later you add to, rather than replace, this statement.

Paul Stephenson
  • 67,682
  • 9
  • 49
  • 51
David Rushton
  • 4,915
  • 1
  • 17
  • 31