In this tutorial, we will understand the concept of Stored Procedures in SQL, learn how to create and call them, and explore how they can improve code reusability and performance.
A Stored Procedure in SQL is a prepared SQL code that you can save and reuse over and over again. So if you have an SQL query that you write over and over again, save it as a Stored Procedure, and then just call it to execute.
You can create a Stored Procedure using the CREATE PROCEDURE
statement. You need to provide the name of the procedure and the SQL statement to be executed.
Example:
CREATE PROCEDURE ProcedureName
AS
SQLStatement
GO;
You can call a Stored Procedure using the EXEC
keyword followed by the procedure name.
Example:
EXEC ProcedureName;
Let's create a simple Stored Procedure that selects everything from a table 'Users'.
CREATE PROCEDURE SelectAllUsers
AS
SELECT * FROM Users;
GO;
To call this Stored Procedure, you would do this:
EXEC SelectAllUsers;
You can create a Stored Procedure with parameters. Let's create a Stored Procedure that selects a user based on a parameter 'UserId'.
CREATE PROCEDURE SelectUser @UserId int
AS
SELECT * FROM Users WHERE Id = @UserId;
GO;
To call this Stored Procedure, you would do this:
EXEC SelectUser 1;
In this tutorial, we have learned about Stored Procedures in SQL, how to create them, and how to call them. We have seen that Stored Procedures can encapsulate logic for data manipulation, which makes our code reusable and improves performance.
For further learning, you could look into more complex use cases of Stored Procedures, such as error handling, using output parameters, and nested Stored Procedures.
Create a Stored Procedure to select users from the 'Users' table where the username is like a given pattern.
Create a Stored Procedure that updates the 'email' of a user in the 'Users' table based on a given 'UserId'.
Create a Stored Procedure that deletes a user from the 'Users' table based on a given 'UserId'.
CREATE PROCEDURE SelectUsersByPattern @Pattern varchar(100)
AS
SELECT * FROM Users WHERE UserName LIKE '%' + @Pattern + '%';
GO;
CREATE PROCEDURE UpdateUserEmail @UserId int, @Email varchar(100)
AS
UPDATE Users SET Email = @Email WHERE Id = @UserId;
GO;
CREATE PROCEDURE DeleteUser @UserId int
AS
DELETE FROM Users WHERE Id = @UserId;
GO;
Practice these exercises and try to come up with your own examples to fully understand the concept. Happy coding!