Author avatar

Chervine Bhiwoo

Writing T-SQL Stored Procedures

Chervine Bhiwoo

  • Feb 5, 2020
  • 7 Min read
  • 9,853 Views
  • Feb 5, 2020
  • 7 Min read
  • 9,853 Views
Data
SQL Server Reporting Services (SSRS)

Introduction

Stored procedures are a collection of Transact-SQL statements stored within the database. They are used to encapsulate oft-used queries, such as conditional statements, loops, and other powerful programming features.

Stored procedures are similar to functions in high-level programming languages. They support both input and output parameters, as well as a return value. Stored procedures can return rows of data or single values.

Types of Stored Procedures

There are two types of stored procedures: 1. System stored procedures 2. Extended stored procedures

Both types are supplied prebuilt within SQL Server. The main difference between the two is that the code for system stored procedures is written in T-SQL and found in the master database included in every SQL Server installation. The code for system extended stored procedures, however, is written in native code, usually C++, and supplied via a dynamic-link library.

Creating Stored Procedures

To create stored procedures, the T-SQL statement CREATE PROCEDURE is used.

1CREATE PROCEDURE procedure_name
2AS
3sql_statement
4GO;
sql

The CREATE PROCEDURE statement must be the only one in the T-SQL batch. All statements from the AS keyword until the end of the script or until the end of the batch (using a batch separator such as GO) will become the body of the stored procedure.

Replacing Stored Procedures

You cannot replace a procedure using the CREATE PROC statement. You need to alter it explicitly using an ALTER PROCEDURE statement or dropping and then recreating it.

1ALTER PROCEDURE procedure_name
2AS
3sql_statement
4GO;
sql

Executing Stored Procedures

The EXECUTE statement is used to execute stored procedures. It is recommended that you qualify the procedure name with the schema name when executing stored procedures. This helps the database engine improve its performance as it does not have to search multiple schemas to find the required procedure. Moreover, it also prevents you from executing the wrong procedure if a database has procedures with the same name in different schemas.

1EXECUTE  schemaname.procedurename;
sql

Deleting Stored Procedures

To remove a stored procedure from the database, the DROP PROCEDURE statement is used. To drop a system extended stored procedure, the procedure sp_dropextendedproc is used,

1DROP PROCEDURE schemaname.procedurename;
sql

Parametrized Stored Procedures

Parametrized stored procedures allow you to pass values in and out of stored procedures. This makes stored procedures reuseable.

Input Parameters

Input parameters are used to exchange data between stored procedures and the code that called the stored procedure. Stored procedures accept input parameters just like parameters are passed to functions in higher languages.

1create procedure getEmployeeDetails
2@empid int
3as
4select name, address, phone
5from employee
6where emplyeeid = @empid;
7Go
sql

Notice how empid is passed inside the stored procedure and used in the query via the parameter of the procedure.

Output Parameters

Output parameters are used to for stored procedures to pass a value back to the caller. To use an output parameter within T-SQL, you must specify the OUTPUT keyword in both the CREATE PROCEDURE statement and the EXECUTE statement.

1create procedure getEmployeeName
2@empid INT
3@empname varchar(50)
4as
5begin
6  select @empname =  name
7  from employee
8  where emplyeeid = @empid;
9end
10Go
sql

Examples

Consider the table of employees below:

idnameaddressagephone
1domUSA3511111111
2brianUSA3022222222
3lettyUSA3233333333

You can use the following script to setup the test data:

1Create table employee (
2id int,
3name varchar(50),
4age int,
5address varchar(100),
6phone int
7);
8GO
9
10insert into employee values (1, 'dom', 35, 'USA', 1111111), (2, 'brian', 30, 'USA', 222222), (3, 'letty', 32, 'USA', 3333333)
11
12select * from employee
sql

Example 1: A stored procedure that returns a list of people older than 31 years old.

1CREATE PROCEDURE getmployeeByage
2AS
3select * from employee
4where age > 31;
5GO
sql

Execute the following command to call the procedure

1execute dbo.getmployeeByage
sql
idnameaddressagephone
1domUSA3511111111
3lettyUSA3233333333

Example 2: Modify the procedure getmployeeByage to take age as a parameter instead of hard-coding it in the T-SQL code.

1ALTER PROCEDURE getmployeeByAge 
2  @age int
3AS
4select * from employee
5where age > @age;
6GO
sql

Pay attention to how the parameter @age is used in the where condition of the select statement.

Example 3: Using the procedure getmployeeByage, display all the employees older than 30 years old.

1execute dbo.getmployeeByAge 30
sql

The result of the execute command would be as follows:

idnameaddressagephone
1domUSA3511111111
3lettyUSA3233333333

Example 4: Write a procedure that returns the average age of employees.

1CREATE PROCEDURE getAvgAge 
2AS
3select avg(age)  from employee
4GO
sql

When you execute the procedure, you should get 32 as result.

Example 5: Modify the procedure getAvgAge to return the result using an output parameter.

1ALTER PROCEDURE getAvgAge 
2  @avgage int OUTPUT
3AS
4BEGIN
5select @avgage = avg(age)  from employee
6END
7GO
sql

Pay attention to the select statement. Here, the value of the parameter @avgage is set by the line @avgage = avg(age).

Example 6: Call the stored procedure getAvgAge and display the result from the output parameter.

1declare @avgageRes int
2execute dbo.getAvgAge @avgage = @avgageRes output
3select @avgageRes
sql

To display the value from the output parameter, you must first declare a variable (@avgageRes), set the output from the procedure to the variable you just declared (@avgage = @avgageRes) and finally, select the result for display.

Conclusion

In this guide, you learned about the basics of stored procedures. This should help you get started and develop more complex understanding going forward.

To learn more about T-SQL, you can also read the following guides:

Happy Coding!