Imagine a situation where we have to use the same query again and again or we have a set of queries that need to run again and again at regular interval. Think of a scenario where you need to incorporate a complex logic into your query before giving out the final output.
Standard SQL queries do not allow the user to include any conditional statements in them. They only allow users to retrieve or modify data stored inside a database.
To apply business logic or apply business logic to store data we need to first get the data, process it and update the database.
The Relational database management system allows developers to create programs to process the data in the database. These are called Stored Procedure.
For the next few pages of the blog, we will learn about stored procedures and their uses in database management.
What is Stored Procedure
Have you heard of a Fibonacci number series? A Fibonacci number series is a series where the following output of the series is the sum of the previous two outputs. The output is somewhat like this:
If you are asked to write logic to provide users an output such as above how would you do that. One easy way of doing it is to write a set of union all statements to give out the output. This is how it would look like
The output is
But as you can well understand this is a hardcoded solution and not flexible. What if you were asked to extend the series to 13 rows?
This is where a stored procedure comes into play. Stored procedure is a special feature of a database management system that allows you to extend the functionality of a database by writing logical program blocks. Now let us rewrite the above code into something like below:
Create PROCEDURE Storedproc
declare @x as int;
declare @y as int;
declare @z as int;
declare @k as int;
while @z <> 15
set @[email protected] + @x;
Execute the procedure as
The output is
As you can see just changing the loop counter, you can change the number of rows as output. This is the beauty of stored procedure.
Types of Stored Procedures
|System defined stored procedure||Extended Stored procedure||User-defined Stored Procedure|
|Preloaded in the system when SQL Server is installed||These are stored procedures that reside in DLLs||Stored procedures developed by individual users|
System defined stored procedure
Some example of system- defined stored procedure is
exec sp_helptext [storedproc_test]
Shows the details of a stored procedure provided as parameter
Gives the details of all the tables present in a database
Gives the dependent object details in multiple rows.
Extended Stored Procedure
To add an extended stored procedure to SQL Server you need to use sp_addextendedproc system stored procedure.
To remove an extended stored procedure from SQL Server you need to use
User-defined Stored Procedure
Here we try to write an SP which gives an output somewhat like below.
Here is the code
create PROCEDURE printstar
-- Add the parameters for the stored procedure here
declare @i int;
declare @k int;
declare @x varchar(max);
while @i <= 5
while @k <= @i
set @[email protected] + '*';
set @[email protected] +1;
set @[email protected]+1;
You execute it with the following command.
Here is the output
Parameterized Stored procedure
Parameterized stored procedures are Stored Procedures where you can pass on some values some outside. Let us take a simple example of adding two numbers using a stored procedure.
The code is as below
create PROCEDURE addtwovalue
declare @sumval int;
set @[email protected] + @val2;
You mention the parameters just after the name of the stored procedure. Here @val1 and @val2 are two parameters.
You pass the parameter into the stored procedure as below
exec addtwovalue 1,2
The output is as below
Stored procedure for insert
Stored procedure can be used for the insert operation.
Let us first create a test table and use it to insert a row with parameters.
create table testtab
name varchar(50), address varchar(50) )
Now let us create a stored procedure to insert a record into the table.
CREATE PROCEDURE sp_inst
insert into testtab values(@name,@address);
To execute the stored procedure
exec sp_inst 'Testname','Testaddr'
Here is the final output
Stored procedure for update
Let us take the same table testtab for the update example.
The code for stored procedure for the update will be as follows.
To run the Procedure we need
exec sp_upd 'Testname','Testaddr1'
The out put is
Stored procedure for Delete
Let us take the same table testtab for the delete example.
The code for the stored procedure for delete will be as follows.
alter PROCEDURE sp_del
delete from testtab where [email protected]
To run the procedure we need
exec sp_del 'Testname'
The output is
Error handling in stored procedure
To catch error in a stored procedure we use Begin Try End Try and Begin Catch and End Catch block.
Here is an example code on the error handling process. The code deliberately generates a divided by zero error and catch and displays the error using the Try Catch block.
CREATE PROCEDURE usp_GetErrorInfo
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
-- Generate divide-by-zero error.
-- Execute error retrieval routine.
The output is
Stored Procedure with Out Parameter
We have seen how to send a parameter into a stored procedure. But how would you send back a value from a stored procedure? The next paragraph deals with the out parameter of stored procedure.
Here is how the code looks like.
Create PROCEDURE dbo.uspGetAddressCount @City nvarchar(30), @AddressCount int OUTPUT
SELECT @AddressCount = count(*)
WHERE City = @City
To execute the stored procedure we need to use the following group of statements
declare @rowCount int
exec uspGetAddressCount 'Bothell', @AddressCount = @rowCount output
The output will look like below
In the above write-up we have tried to give you an overview of different types of stored procedures and how they can be used. It is not a comprehensive guide but this would give the reader a sneak pick on the definition of stored procedure, their capabilities, types and how to use them.
I love to learn new things and also like sharing my knowledge with others. As an experienced IT Professional I like to update myself constantly with new and upcoming technologies. The database management system is one of my favorite subjects which I constantly explore.
Receive Latest Materials and Offers on SQL Server Course