Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Writing T-SQL Stored Procedures

Feb 5, 2020 • 7 Minute Read

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.

      CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
    

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.

      ALTER PROCEDURE procedure_name
AS
sql_statement
GO;
    

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.

      EXECUTE  schemaname.procedurename;
    

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,

      DROP PROCEDURE schemaname.procedurename;
    

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.

      create procedure getEmployeeDetails
@empid int
as
select name, address, phone
from employee
where emplyeeid = @empid;
Go
    

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.

      create procedure getEmployeeName
@empid INT
@empname varchar(50)
as
begin
  select @empname =  name
  from employee
  where emplyeeid = @empid;
end
Go
    

Examples

Consider the table of employees below:

idnameaddressagephone
1domUSA3511111111
2brianUSA3022222222
3lettyUSA3233333333

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

      Create table employee (
id int,
name varchar(50),
age int,
address varchar(100),
phone int
);
GO

insert into employee values (1, 'dom', 35, 'USA', 1111111), (2, 'brian', 30, 'USA', 222222), (3, 'letty', 32, 'USA', 3333333)

select * from employee
    

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

      CREATE PROCEDURE getmployeeByage
AS
select * from employee
where age > 31;
GO
    

Execute the following command to call the procedure

      execute dbo.getmployeeByage
    
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.

      ALTER PROCEDURE getmployeeByAge 
  @age int
AS
select * from employee
where age > @age;
GO
    

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.

      execute dbo.getmployeeByAge 30
    

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.

      CREATE PROCEDURE getAvgAge 
AS
select avg(age)  from employee
GO
    

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.

      ALTER PROCEDURE getAvgAge 
  @avgage int OUTPUT
AS
BEGIN
select @avgage = avg(age)  from employee
END
GO
    

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.

      declare @avgageRes int
execute dbo.getAvgAge @avgage = @avgageRes output
select @avgageRes
    

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:

Introduction to T-SQL Querying Writing SELECT Queries Querying Multiple Tables in SQL Server

Happy Coding!