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:
ALTER
of the stored procedure doesn't happen as planned;Using SET NOCOUNT ON can improve performance because network traffic can be reduced. SET NOCOUNT ON prevents SQL Server from sending DONE_IN_PROC message for each statement in a stored procedure or batch of SQL statements.
SET NOCOUNT ON prevents the sending of DONEINPROC messages to the client for each statement in a stored procedure.
Answer: Stored Procedures can not be executed from within Functions. Stored Procedures can not be executed via Queries.
The procedure calls are quick and efficient as stored procedures are compiled once and stored in executable form. Hence the response is quick. The executable code is automatically cached, hence lowers the memory requirements. Since the same piece of code is used again and again so, it results in higher productivity.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With