| Lesson 4 | Creating stored procedures | User Defined |
| Objective | Understand how to create a user-defined stored procedure in SQL Server. |
dbo.usp_DoWork).CREATE OR ALTER for idempotent deployments.SET NOCOUNT ON; in most procedures to reduce rowcount chatter to client applications.
CREATE OR ALTER PROCEDURE.
The following example shows a modern, deployment-friendly template.
The `CREATE OR ALTER` syntax for stored procedures was introduced in SQL Server 2016 Service Pack 1 (November 2016) to simplify database development by eliminating the need for conditional logic that checks whether a procedure exists before creating or modifying it. This feature makes deployment scripts idempotent, allowing them to be executed repeatedly without errors—a significant improvement for teams practicing continuous integration and deployment. SQL Server versions prior to 2016 SP1, including SQL Server 2012, 2014, and the original 2016 RTM release, cannot use this syntax and must rely on workarounds like `DROP IF EXISTS` followed by `CREATE`, or conditional checks against system catalog views. Organizations running older SQL Server versions should consider upgrading to take advantage of this and other modern T-SQL enhancements that align database development with contemporary DevOps practices.
CREATE OR ALTER PROCEDURE dbo.procedure_name
@parameter1 data_type = default,
@parameter2 data_type OUTPUT
AS
BEGIN
-- Transact-SQL statements
END;
CREATE OR ALTER PROCEDURE creates the procedure if it does not exist, or alters it if it already exists. This supports repeatable deployments.dbo is the schema. Schema-qualify procedure names so SQL Server resolves the object consistently and predictably.procedure_name is the procedure identifier. Use a clear naming convention (many teams use a prefix like usp_ for user stored procedures).@parameter1 is an input parameter name. Parameters are the primary mechanism for passing values into a stored procedure.data_type defines the parameter datatype (for example, int, nvarchar(50), datetime2). Every parameter must declare a datatype.= default assigns a default value to the parameter, used when the caller does not supply an explicit value.OUTPUT marks a parameter as output-capable so the procedure can return a value through that parameter to the caller.AS begins the procedure body definition (the executable T-SQL section).BEGIN … END forms the procedure body block that contains one or more T-SQL statements implementing the unit of work.-- Transact-SQL statements is where you implement the logic (queries, inserts/updates, validation, transactions, and error handling as required).SET NOCOUNT ON and a simple parameterized query.
CREATE OR ALTER PROCEDURE dbo.usp_GetEmployeeById
@EmployeeId int
AS
BEGIN
SET NOCOUNT ON;
SELECT e.EmployeeId, e.FirstName, e.LastName, e.DepartmentId
FROM dbo.Employees AS e
WHERE e.EmployeeId = @EmployeeId;
END;
EXEC dbo.usp_GetEmployeeById @EmployeeId = 42;