Paramclasses Academy - Blog

Tutorials Details

←
Post 26 of 40
→

Stored Procedures in SQL Server: Create and Execute Step by Step with Examples

Stored Procedures in SQL Server: Create and Execute Step by Step with Examples

November 18, 2026

???? Stored Procedures in SQL Server: Create and Execute Step by Step

???? Introduction to Stored Procedures

A Stored Procedure in Microsoft SQL Server is a pre-written collection of SQL statements stored inside the database. It can be executed whenever required to perform database operations such as retrieving, inserting, updating, and deleting records.

Instead of writing the same SQL query repeatedly, developers can create a stored procedure once and execute it whenever needed.

Stored Procedures are commonly used in Student Management Systems, Employee Management Systems, Inventory Management Systems, Billing Applications, and Web Applications.

At Param Classes, students learn SQL Server concepts through practical examples and real-world database operations.


???? What You Will Learn

After completing this tutorial, you will understand:

  1. What is a Stored Procedure in SQL Server?

  2. Why do we use Stored Procedures?

  3. Advantages of Stored Procedures.

  4. Basic Stored Procedure syntax.

  5. How to create a Stored Procedure.

  6. How to execute a Stored Procedure.

  7. How to use input parameters.

  8. How to use output parameters.

  9. How to alter and delete Stored Procedures.

  10. How to implement error handling using TRY...CATCH.

  11. Practical Stored Procedure examples.


???? 1. What Is a Stored Procedure in SQL Server?

A Stored Procedure is a database object that contains one or more SQL statements saved under a specific name.

For example, suppose you have an Employee table containing employee records. Every time you want to display all employees, you could write:

SELECT * FROM Employees;

Instead of writing this query repeatedly, you can create a Stored Procedure:

CREATE PROCEDURE GetAllEmployees
AS
BEGIN
    SELECT * FROM Employees;
END;

Now you can execute the procedure whenever required:

EXEC GetAllEmployees;

Remember: CREATE PROCEDURE creates the procedure, whereas EXEC or EXECUTE runs it.


???? 2. Why Do We Use Stored Procedures?

Stored Procedures help developers organize and reuse SQL logic.

Common reasons to use Stored Procedures:

  • ♻️ Code Reusability: Write SQL logic once and execute it multiple times.

  • ⚡ Performance: SQL Server can reuse cached execution plans when appropriate.

  • ???? Security: Permissions can be granted on procedures without necessarily granting direct access to underlying tables.

  • ????️ Maintainability: Database logic can be managed in one place.

  • ???? Less Repeated Code: Applications can call a procedure instead of sending lengthy SQL statements repeatedly.

  • ✅ Error Handling: Use TRY...CATCH to handle runtime errors.


???? 3. Basic Syntax of Stored Procedure

The basic syntax is:

CREATE PROCEDURE ProcedureName
AS
BEGIN
    -- SQL Statements
END;
GO

Explanation:

Keyword Description
CREATE PROCEDURE Creates a new stored procedure
ProcedureName Name of the procedure
AS Starts the procedure definition
BEGIN Starts the SQL statement block
END Ends the procedure block
GO Separates batches in tools such as SSMS

Important: GO is a batch separator recognized by SQL Server tools such as SSMS. It is not a Transact-SQL statement sent to the database engine.


???? 4. Create a Database and Employee Table

Let's understand Stored Procedures using a practical Employee Management example.

Step 1: Create a database

CREATE DATABASE EmployeeDB;
GO

USE EmployeeDB;
GO

Step 2: Create an Employees table

CREATE TABLE Employees
(
    EmployeeID INT PRIMARY KEY IDENTITY(1,1),
    EmployeeName VARCHAR(100) NOT NULL,
    Department VARCHAR(50),
    Salary DECIMAL(10,2)
);
GO

Step 3: Insert sample records

INSERT INTO Employees
(EmployeeName, Department, Salary)
VALUES
('Rahul', 'IT', 35000),
('Amit', 'HR', 30000),
('Priya', 'IT', 45000),
('Neha', 'Finance', 40000),
('Rohit', 'Marketing', 32000);
GO

Step 4: Display employee records

SELECT * FROM Employees;

Now our EmployeeDB database is ready for Stored Procedure examples.


???? 5. How to Create Your First Stored Procedure

Let's create a procedure that displays all employee records.

CREATE PROCEDURE GetAllEmployees
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        EmployeeID,
        EmployeeName,
        Department,
        Salary
    FROM Employees;
END;
GO

Explanation:

  • CREATE PROCEDURE creates a new procedure.

  • GetAllEmployees is the procedure name.

  • SET NOCOUNT ON suppresses row-count messages.

  • SELECT retrieves employee information.

  • BEGIN and END define the procedure body.

▶️ Execute the Stored Procedure

EXEC GetAllEmployees;

Expected Output:

EmployeeID EmployeeName Department Salary
1 Rahul IT 35000
2 Amit HR 30000
3 Priya IT 45000
4 Neha Finance 40000
5 Rohit Marketing 32000

You can also execute it using:

EXECUTE GetAllEmployees;

Both EXEC and EXECUTE are valid.


???? 6. Stored Procedure with Input Parameters

An Input Parameter allows us to pass a value to a Stored Procedure when executing it.

For example, suppose you want to retrieve employees from a particular department.

CREATE PROCEDURE GetEmployeesByDepartment
    @Department VARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        EmployeeID,
        EmployeeName,
        Department,
        Salary
    FROM Employees
    WHERE Department = @Department;
END;
GO

▶️ Execute the Procedure

EXEC GetEmployeesByDepartment
    @Department = 'IT';

Expected Output:

EmployeeID EmployeeName Department Salary
1 Rahul IT 35000
3 Priya IT 45000

Explanation:

  • @Department is an input parameter.

  • VARCHAR(50) defines its data type.

  • 'IT' is the value passed during execution.

  • The WHERE clause returns only matching department records.

???? Another Example

EXEC GetEmployeesByDepartment
    @Department = 'HR';

This returns employees working in the HR department.


???? 7. Stored Procedure with Multiple Parameters

A procedure can accept multiple input parameters.

Let's create a procedure that searches employees using department and minimum salary.

CREATE PROCEDURE GetEmployeesBySalary
    @Department VARCHAR(50),
    @MinSalary DECIMAL(10,2)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        EmployeeID,
        EmployeeName,
        Department,
        Salary
    FROM Employees
    WHERE Department = @Department
      AND Salary >= @MinSalary;
END;
GO

▶️ Execute the Procedure

EXEC GetEmployeesBySalary
    @Department = 'IT',
    @MinSalary = 40000;

Expected Output:

EmployeeID EmployeeName Department Salary
3 Priya IT 45000

Important: When named parameters are used, their values can be supplied in a different order from their definition.


???? 8. Stored Procedure with Default Parameter Values

SQL Server allows you to define default values for parameters.

CREATE PROCEDURE GetEmployeesByDepartmentDefault
    @Department VARCHAR(50) = 'IT'
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        EmployeeID,
        EmployeeName,
        Department,
        Salary
    FROM Employees
    WHERE Department = @Department;
END;
GO

▶️ Execute Without Passing a Parameter

EXEC GetEmployeesByDepartmentDefault;

The procedure uses the default department value, which is IT.

▶️ Execute With a Different Parameter

EXEC GetEmployeesByDepartmentDefault
    @Department = 'Finance';

Now the procedure returns employees from the Finance department.


???? 9. Stored Procedure with OUTPUT Parameter

An OUTPUT Parameter allows a procedure to return a value to the calling SQL statement.

For example, let's calculate the total number of employees.

CREATE PROCEDURE GetEmployeeCount
    @TotalEmployees INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    SELECT @TotalEmployees = COUNT(*)
    FROM Employees;
END;
GO

▶️ Execute the Procedure

DECLARE @Count INT;

EXEC GetEmployeeCount
    @TotalEmployees = @Count OUTPUT;

SELECT @Count AS TotalEmployees;

Expected Output:

TotalEmployees
5

Remember: The OUTPUT keyword is required both in the procedure definition and when passing the output parameter during execution.


???? 10. How to Modify a Stored Procedure Using ALTER

Sometimes we need to change an existing Stored Procedure.

SQL Server provides the ALTER PROCEDURE statement.

Example:

ALTER PROCEDURE GetAllEmployees
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        EmployeeID,
        EmployeeName,
        Department,
        Salary
    FROM Employees
    ORDER BY Salary DESC;
END;
GO

▶️ Execute the Modified Procedure

EXEC GetAllEmployees;

Now employee records are displayed in descending order of salary.

Note: ALTER PROCEDURE modifies an existing procedure. It does not create a new one.


???? 11. CREATE OR ALTER PROCEDURE

SQL Server also supports CREATE OR ALTER PROCEDURE.

It creates the procedure if it does not exist or modifies it if it already exists.

CREATE OR ALTER PROCEDURE GetAllEmployees
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        EmployeeID,
        EmployeeName,
        Department,
        Salary
    FROM Employees;
END;
GO

Compatibility Note: CREATE OR ALTER PROCEDURE is supported in SQL Server 2016 SP1 and later versions.


???? 12. Stored Procedure for INSERT Operation

Stored Procedures can also insert new records into a table.

Let's create a procedure to add a new employee.

CREATE PROCEDURE InsertEmployee
    @EmployeeName VARCHAR(100),
    @Department VARCHAR(50),
    @Salary DECIMAL(10,2)
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO Employees
    (
        EmployeeName,
        Department,
        Salary
    )
    VALUES
    (
        @EmployeeName,
        @Department,
        @Salary
    );
END;
GO

▶️ Execute the Procedure

EXEC InsertEmployee
    @EmployeeName = 'Karan',
    @Department = 'IT',
    @Salary = 50000;

Verify the Inserted Record

SELECT * FROM Employees;

The new employee record will appear in the table.


???? 13. Stored Procedure for UPDATE Operation

Let's create a procedure to update an employee's salary.

CREATE PROCEDURE UpdateEmployeeSalary
    @EmployeeID INT,
    @NewSalary DECIMAL(10,2)
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE Employees
    SET Salary = @NewSalary
    WHERE EmployeeID = @EmployeeID;
END;
GO

▶️ Execute the Procedure

EXEC UpdateEmployeeSalary
    @EmployeeID = 1,
    @NewSalary = 55000;

Verify Updated Data

SELECT * FROM Employees
WHERE EmployeeID = 1;

The salary of employee ID 1 is now updated to 55000.


???? 14. Stored Procedure for DELETE Operation

We can also delete employee records using a Stored Procedure.

CREATE PROCEDURE DeleteEmployee
    @EmployeeID INT
AS
BEGIN
    SET NOCOUNT ON;

    DELETE FROM Employees
    WHERE EmployeeID = @EmployeeID;
END;
GO

▶️ Execute the Procedure

EXEC DeleteEmployee
    @EmployeeID = 5;

Verify Deleted Data

SELECT * FROM Employees;

The record with EmployeeID 5 will be deleted.

⚠️ Important: Always verify the record and its ID before executing a DELETE procedure, especially when working with production databases.


???? 15. Error Handling in Stored Procedures Using TRY...CATCH

SQL Server provides TRY...CATCH blocks to handle runtime errors.

Let's create a procedure that inserts an employee and handles errors.

CREATE PROCEDURE SafeInsertEmployee
    @EmployeeName VARCHAR(100),
    @Department VARCHAR(50),
    @Salary DECIMAL(10,2)
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY

        INSERT INTO Employees
        (
            EmployeeName,
            Department,
            Salary
        )
        VALUES
        (
            @EmployeeName,
            @Department,
            @Salary
        );

        PRINT 'Employee inserted successfully';

    END TRY

    BEGIN CATCH

        SELECT
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_MESSAGE() AS ErrorMessage;

    END CATCH;
END;
GO

▶️ Execute the Procedure

EXEC SafeInsertEmployee
    @EmployeeName = 'Ankit',
    @Department = 'IT',
    @Salary = 42000;

If a runtime error occurs inside the TRY block, SQL Server transfers control to the CATCH block.

Useful Error Functions:

Function Description
ERROR_NUMBER() Returns the error number
ERROR_MESSAGE() Returns the error message
ERROR_LINE() Returns the line number
ERROR_PROCEDURE() Returns the procedure name

???? 16. How to Delete a Stored Procedure

If a Stored Procedure is no longer required, you can remove it using DROP PROCEDURE.

DROP PROCEDURE GetAllEmployees;
GO

To avoid an error when the procedure does not exist, use:

DROP PROCEDURE IF EXISTS GetAllEmployees;
GO

Important: Dropping a procedure removes its definition from the database. It does not delete the employee records stored in the Employees table.


???? 17. How to View Stored Procedures in SQL Server Management Studio (SSMS)

You can view Stored Procedures through SQL Server Management Studio.

Follow these steps:

  1. Open SQL Server Management Studio (SSMS).

  2. Connect to your SQL Server instance.

  3. Expand the Databases folder.

  4. Select your database, such as EmployeeDB.

  5. Expand the Programmability folder.

  6. Expand Stored Procedures.

  7. Find your procedure in the list.

  8. Right-click it to view options such as Modify or Execute Stored Procedure.

You can also find user-created stored procedures using:

SELECT
    name,
    create_date,
    modify_date
FROM sys.procedures
ORDER BY name;

???? 18. Stored Procedure vs SQL Query

Feature SQL Query Stored Procedure
Storage Usually sent when needed Stored in database
Reusability Query must be sent again Can be called repeatedly
Parameters Can use variables Supports input and output parameters
Logic Individual SQL statements Can contain multiple statements and control flow
Error Handling Can use TRY...CATCH in a batch Can use TRY...CATCH inside procedure
Execution Run SQL statement Execute using EXEC or EXECUTE

???? 19. Best Practices for Stored Procedures

Follow these practices when developing SQL Server applications:

  1. Use Meaningful Names: Give procedures clear names such as GetAllEmployees or InsertEmployee.

  2. Use SET NOCOUNT ON: Place it near the beginning of the procedure body.

  3. *Avoid SELECT : Select only the required columns.

  4. Use Parameters: Avoid hardcoding values that should be supplied dynamically.

  5. Handle Errors: Use TRY...CATCH for appropriate runtime error handling.

  6. Use Transactions Carefully: Use BEGIN TRANSACTION, COMMIT and ROLLBACK when multiple operations must succeed or fail together.

  7. Follow Security Practices: Grant only the required permissions.

  8. Test Before Deployment: Test procedures with valid, invalid and boundary input values.


???? 20. Frequently Asked Questions (FAQs)

Q1. What is a Stored Procedure in SQL Server?

A Stored Procedure is a collection of SQL statements saved as a database object that can be executed whenever required.

Q2. Which command is used to create a Stored Procedure?

The CREATE PROCEDURE statement is used to create a Stored Procedure.

Q3. How do you execute a Stored Procedure?

Use the EXEC or EXECUTE command.

Example:

EXEC GetAllEmployees;

Q4. What is the difference between CREATE and ALTER PROCEDURE?

CREATE PROCEDURE creates a new procedure, while ALTER PROCEDURE modifies an existing procedure.

Q5. Can a Stored Procedure accept multiple parameters?

Yes. A Stored Procedure can accept multiple input parameters and can also use output parameters.

Q6. What is an OUTPUT Parameter?

An OUTPUT Parameter allows a Stored Procedure to return a value to the calling SQL statement or application.

Q7. Can we perform INSERT, UPDATE and DELETE operations inside Stored Procedures?

Yes. Stored Procedures can perform all these operations when the required permissions and database conditions are satisfied.

Q8. What is SET NOCOUNT ON?

It prevents SQL Server from sending row-count messages after statements such as INSERT, UPDATE and DELETE. It does not prevent the procedure from returning SELECT result sets.

Q9. Can we delete a Stored Procedure?

Yes. Use DROP PROCEDURE to remove a Stored Procedure.

Q10. Are Stored Procedures useful in real-world applications?

Yes. They are commonly used in enterprise applications, web applications, reporting systems and database-driven software.


???? Conclusion

In this tutorial, we learned Stored Procedures in SQL Server step by step, including how to create, execute, modify and delete procedures.

We also explored Input Parameters, Multiple Parameters, Default Parameters, OUTPUT Parameters, INSERT, UPDATE, DELETE operations and TRY...CATCH error handling with practical SQL examples.

Stored Procedures are an important part of SQL Server development because they help developers organize database logic, reuse SQL code and manage database operations efficiently.

At Param Classes, we focus on practical database training so students can understand SQL Server concepts and apply them in real-world projects.

Keep Learning, Keep Practicing, and Build Your Database Development Skills with Param Classes!


???? Suggested Learning Resources

  • Microsoft Learn – CREATE PROCEDURE (Transact-SQL)

  • Microsoft Learn – Execute a Stored Procedure

  • Microsoft Learn – Specify Parameters in a Stored Procedure

Practice Task: Create a Student Management Database and write Stored Procedures to insert, display, update and delete student records. Also create one procedure that accepts a StudentID parameter and another that returns the total number of students using an OUTPUT parameter.

←
Post 26 of 40
→