10. Stored Procedures

Stored Procedures in SQL

A stored procedure is a series of SQL statements compiled and saved to the database. By encapsulating complex logic in one place, they offer several advantages, such as faster execution, reduced network traffic, and the ability to include conditional logic (e.g., IF...ELSE statements) and parameters.

Key Points about Stored Procedures

Procedure Example: Naming Convention

It is common to prefix stored procedure names with sp_ to indicate they are procedures, though this is more of a convention than a strict requirement.

Controlling Output Messages

SET NOCOUNT ON;

Prevents SQL Server from returning the “X row(s) affected” message after each statement.

@@ROWCOUNT

@@ROWCOUNT is a system variable that tracks how many rows were affected by the last executed statement in a batch.

Status Codes

Procedures typically return a status code to indicate success or an error:

Executing Dynamic SQL inside Procedures

sp_sqlexecute (or sp_executesql in many SQL Server systems) can be used to run SQL statements that are built dynamically, often passed as NVARCHAR strings.

Stored Procedures vs. Functions

References

The content in this document is based on the original notes provided in Azerbaijani. For further details, you can refer to the original document using the following link:

Original Note - Azerbaijani Version