| Lesson 6 | Modifying Stored Procedures in SQL Server |
| Objective | Describe how to modify a user-defined stored procedure. |
Business rules evolve over time, and stored procedures must often be updated to reflect new validation logic, additional data changes, or revised error handling. In SQL Server 2022, stored procedures are typically modified using SQL Server Management Studio (SSMS) and Transact-SQL.
Earlier tools such as Enterprise Manager have been replaced by SSMS.
Today, the recommended approach is to modify procedures directly with T-SQL.
SQL Server 2016 and later also support CREATE OR ALTER PROCEDURE,
which simplifies deployment by avoiding separate create and alter scripts.
CREATE OR ALTER PROCEDURE dbo.usp_DeleteEmployee
@EmployeeID int
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM dbo.Employees WHERE EmployeeID = @EmployeeID)
BEGIN
DELETE FROM dbo.Timesheets
WHERE EmployeeID = @EmployeeID;
DELETE FROM dbo.Employees
WHERE EmployeeID = @EmployeeID;
END
ELSE
BEGIN
THROW 50001, 'Employee ID does not exist.', 1;
END
END;
When you need to explicitly modify an existing procedure, use ALTER PROCEDURE.
The syntax is largely identical to CREATE PROCEDURE, but it preserves
permissions and dependencies.
ALTER PROCEDURE procedure_name
(
@parameter data_type [ = default ] [ OUTPUT ]
, ...
)
[WITH RECOMPILE]
AS
BEGIN
-- Transact-SQL statements
END;
dbo.usp_Name) is strongly recommended.
BEGIN…END block.
Although it is technically possible to drop and recreate a stored procedure,
this approach removes all existing permissions and can break dependencies.
Using ALTER PROCEDURE or CREATE OR ALTER preserves security
settings and is the preferred method in SQL Server 2022.
The following example modifies a procedure to delete related rows from multiple tables
and uses modern error handling with THROW instead of RAISERROR.
ALTER PROCEDURE dbo.usp_DeleteEmployee
@EmployeeID int
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM dbo.Employees WHERE EmployeeID = @EmployeeID)
BEGIN
DELETE FROM dbo.Timesheets
WHERE EmployeeID = @EmployeeID;
DELETE FROM dbo.Employees
WHERE EmployeeID = @EmployeeID;
END
ELSE
BEGIN
THROW 50002, 'Employee ID does not exist.', 1;
END
END;
In the next lesson, you will learn how to safely remove stored procedures from a SQL Server database.