Stored procedures
You SHOULD: -
-
Use meaningful names to indicate the purpose of procedures & parameters. Be verbose if needed.
-
Match parameter datatypes to the underlying data to avoid implicit conversion.
-
Include a comment header to indicate the procedure's purpose and use. Include an example call if possible.
-
Enclose procedures with
BEGIN ENDblocks after theASkeyword. -
Add the
SET NOCOUNT ONstatement before any Data Manipulation Language statements unless you have good reason for not doing so. -
Use
SET XACT_ABORT ON. It terminates and rollbacks the entire transaction when a T-SQL statement raises a run-time error. -
Declare variables, table variables and temp tables at the start of a procedure1.
-
Use
BEGINandENDafterIF, even if only one statement is covered. This makes the code clearer and avoids errors if further statements are added to theIFblock later. -
Use table variables for transitory tables with less than 1000 rows.
-
Use temporary tables for transitory tables with more than 1000 rows.
-
Use explicit transactions when updating data.
-
Use SavePoints within a transaction. The use of SavePoint can allow you to rollback a series of statements within a transaction.
-
Pass parameters explicitly to Stored Procedures and
EXECUTEstatements wherever possible.
You SHOULD NOT:-
-
Set the
ANSI_NULLSoption. It should normally be set toONand is deprecated by Microsoft and not supported for certain indexes. -
Set the
QUOTED_IDENTIFIERoption. It has no effect and should normally be set toON. -
Declare variables you never use.
-
Use
CURSORs andWHILEclauses. -
Use Table Variables, Temporary Tables, Common Table Expressions and Subqueries without understanding their impact on performance.
-
Use nested transactions. A
ROLLBACKof a nested transaction can affect more than just the statements executed. -
Return multiple result sets.
-
Supply stored procedures with a wide range of data parameters. SQL Server compiles these to a single query plan.
Further reading and information
Discontinued database engine functionality - SQL Server | Microsoft Learn
Temporary Tables in SQL Server - Simple Talk (red-gate.com )
-
Note: This is contrary to the general coding standards. But Redgate discourages interweaving Data Definition Language (e.g.
CREATE TABLE) and Data Manipulation Language statements (e.g.SELECT). ↩