Understanding Database Stored Procedures

This article discusses stored procedures and how to create, update, and delete stored procedures using SQL.

What is a Stored Procedure?

A stored procedure is a database object that contains one or more SQL statements. In this article you will get an idea on how to create and use stored procedures and also highlighted on how to use stored procedures.

The first time a stored procedure is executed; each SQL statement it contains is compiled and executed to create an execution plan. Then procedure is stored in compiled form with in the database. For each subsequent execution, the SQL statements are executed without compilation, because they are precompiled. This makes the execution of stored procedure faster than the execution of an equivalent SQL script.

To execute a stored procedure you can use EXEC statement.


When you run this script in Pubs database you will get the following message in Query Analyzer.

The Command(s) completed successfully.

Now you are ready to call/execute this procedure from Query Analyzer.

EXEC spGetShashi

This stored procedure creates a result set and returns to client.

You can call a stored procedure from within another stored procedure. You can even call a stored procedure from within itself. This technique is called a recursive call in programming. One of the advantages of using stored procedures is that application programmers and end users don't need to know the structure of the database or how to code SQL. Another advantage of it is they can restrict and control access to a database.

Classification of Stored Procedures

The classification of stored procedures is depends on the Where it is Stored. Based on this you can divide it in 4 sections.

  • System stored procedures
  • Local stored procedures
  • Temporary stored procedures
  • Extended stored procedures

System stored procedures are stored in the Master database and are typically named with a sp_ prefix. They can be used to perform variety of tasks to support SQL Server functions that support external application calls for data in the system tables, general system procedures for database administration, and security management functions.
For example, you can view the contents of the stored procedure by calling

sp_helptext [StoredProcedure_Name].

There are hundreds of system stored procedures included with SQL Server. For a complete list of system stored procedures, refer to "System Stored Procedures" in SQL Server Books Online.

Local stored procedures are usually stored in a user database and are typically designed to complete tasks in the database in which they reside. While coding these procedures don't use sp_ prefix to you stored procedure it will create a performance bottleneck. The reason is when you can any procedure that is prefixed with sp_ it will first look at in the mater database then comes to the user local database.

A temporary stored procedure is all most equivalent to a local stored procedure, but it exists only as long as SQL Server is running or until the connection that created it is not closed. The stored procedure is deleted at connection termination or at server shutdown. This is because temporary stored procedures are stored in the TempDB database. TempDB is re-created when the server is restarted.

There are three types of temporary stored procedures: local , global, and stored procedures created directly in TempDB.

A local temporary stored procedure always begins with #, and a global temporary stored procedure always begins with ##. The execution scope of a local temporary procedure is limited to the connection that created it. All users who have connections to the database, however, can see the stored procedure in Query Analyzer. There is no chance of name collision between other connections that are creating temporary stored procedures. To ensure uniqueness, SQL Server appends the name of a local temporary stored procedure with a series of underscore characters and a connection number unique to the connection. Privileges cannot be granted to other users for the local temporary stored procedure. When the connection that created the temporary stored procedure is closed, the procedure is deleted from TempDB.

Any connection to the database can execute a global temporary stored procedure. This type of procedure must have a unique name, because all connections can execute the procedure and, like all temporary stored procedures, it is created in TempDB. Permission to execute a global temporary stored procedure is automatically granted to the public role and cannot be changed. A global temporary stored procedure is almost as volatile as a local temporary stored procedure. This procedure type is removed when the connection used to create the procedure is closed and any connections currently executing the procedure have completed.

Temporary stored procedures created directly in TempDB are different than local and global temporary stored procedures in the following ways:

  • You can configure permissions for them.
  • They exist even after the connection used to create them is terminated.
  • They aren't removed until SQL Server is shut down.

Because this procedure type is created directly in TempDB, it is important to fully qualify the database objects referenced by Transact-SQL commands in the code. For example, you must reference the Authors table, which is owned by dbo in the Pubs database, as pubs.dbo.authors.

--create a local temporary stored procedure.

SELECT * from [pubs].[dbo].[shashi]

--create a global temporary stored procedure.

SELECT * from [pubs].[dbo].[shasi]

-create a temporary stored procedure that is local to tempdb.

SELECT * from [pubs].[dbo].[shashi]

An extended stored procedure uses an external program, compiled as a 32-bit dynamic link library (DLL), to expand the capabilities of a stored procedure. A number of system stored procedures are also classified as extended stored procedures. For example, the xp_sendmail program, which sends a message and a query result set attachment to the specified e-mail recipients, is both a system stored procedure and an extended stored procedure. Most extended stored procedures use the xp_ prefix as a naming convention. However, there are some extended stored procedures that use the sp_ prefix, and there are some system stored procedures that are not extended and use the xp_ prefix. Therefore, you cannot depend on naming conventions to identify system stored procedures and extended stored procedures.

Use the OBJECTPROPERTY function to determine whether a stored procedure is extended or not. OBJECTPROPERTY returns a value of 1 for IsExtendedProc, indicating an extended stored procedure, or returns a value of 0, indicating a stored procedure that is not extended.

USE MasterSELECT OBJECTPROPERTY(object_id('xp_sendmail'), 'IsExtendedProc')

Create a Stored Procedure 

CREATE PROCEDURE SQL statement is used to create an SP. When the CREATE PROCEDURE statement is executed, the syntax of the SQL statements within the procedure is checked. If you have made a coding error the system responds with an appropriate message and the procedure is not created.

The Syntax of the CREATE PROCEDURE statement

AS sql_statements

You can use CREATE PROCEDURE statement to create a stored procedure in the database. The name of the stored procedure can be up to 128 characters and is typically prefixed with the letters sp.

If you look at the above options like AS, RECOMPILE, ENCRYPTION these are having some significance meaning to it.

The AS clause contains the SQL statements to be executed by the stored procedure. Since a stored procedure must consist of single batch.

Recompile is used when you want to compile the stored procedure every time when you call. This comes into the picture when one doesn't want to catch the execution plan of stored procedure in the database. Encryption implies that you want to hide this code so that no one can see it. This is very important when you want to distribute the code across the globe or when you want to sell this code to other vendors. But make sure you have original copy it; because once you encrypted it no one can decrypt it.

Apart from the stored procedure that store in the database a permanent entity you can create stored procedure as per you session. That means as long the as the session is alive then the stored procedure is available in the memory means in the database.
Once the session ends the stored procedure is vanished this actually depends on what type of stored procedure you have chosen to create it.

Stored procedure provide for two different types of parameters: input parameters and Output Parameters. An input Parameter is passed to the stored procedure from the calling program. An output parameter is returned to the calling program from the stored procedure. You can identify an output parameter with the OUTPUT keyword. If this keyword is omitted the parameter is assumed to be an input parameter.

You can declare an input parameter so that it requires a value or so that its value is optional. The value of a required parameter must be passed to the stored procedure from the calling program on an error occurs. The value of an optional parameter doesn't need to be passed from the calling program. You identify an optional parameter by assigning a default value to it. Then if a value isn't passed from the calling program, the default value is used. You can also use output parameter as input parameters. That is you can pass a value from the calling program to the stored procedure through an output parameter. However is not advisable to pass parameters to Output parameters.

The syntax for declaring the parameters

@Parameter_name_1 data_type [= default] [OUTPUT]
[, @Parameter_name_2 data_type [= default] [OUTPUT]

Parameter declarations:
@FirstName varchar(50) -- Input parameter that accepts a string.
@LastName varchar(50) -- Output Parameter that returns a string.

Create Procedure statement that uses an input and an output parameter.

                       @FirstName varchar(50),
                       @LastName varchar(50)
SELECT  @LastName= ln_Name
WHERE   fn_name = @FirstName

Create procedure statement that uses an optional parameter.

                       @LastName varchar(50),
                       @FirstName varchar(50) = 'shashi'
SELECT  @LastName= ln_Name
WHERE   fn_name = @FirstName

A stored procedure can declare up to 2100 parameters. If you declare two or more parameters, the declarations must be separated by commas.

Delete or Update a Stored Procedure

You use DROP PROC SQL statement to delete one or more stored procedures from database. To update the stored procedure you use ALTER PROC SQL statement.

The syntax of the DROP PROC statement

DROP {PROC|PROCEDURE} Procedure_name [, ]

The syntax of the ALTER PROC statement

ALTER {PROC|PROCEDURE} Procedure_name[Parameter_declaration][WITH {RECOMPILE|ENCRYPTION|RECOMPILE, ENCRYPTION}]AS sql_statements

When you delete a procedure any security permission that are assigned to the procedure are also deleted. In that case you will want to use the ALTER PROC statement to modify the procedure and preserve permissions.

Calling stored procedure with Parameters

To pass parameter values to a stored procedure, you code the values in the EXEC statement after the procedure name. You can pass the parameters either by position or by name.

Passing parameters by Name:

Write the following code in Query Analyzer

DECLARE @LN VARCHAR(100)EXEC spGetShashi @FirstName = 'shashi', @LastName = @LN OUTPUT

Passing parameters by Position:

DECLARE @LN VARCHAR(100)EXEC spGetShashi @LN OUTPUT, 'shahsi'

In fact you can use both notations to pass parameters to stored procedures when you are calling. To pass parameters by position, list them in the same order as they appear in the CREATE PROCEDURE statement and separate them with commas. When you use this technique, you can omit optional parameters only if they are declared after any required parameters.

To use an output parameter in the calling program, you must declare a variable to store its value. Then you use the name of the variable in the EXEC statement and you code the OUTPUT keyword after it to identify it as an output parameter.

Handling error in stored procedure

In addition to passing output parameters back to the calling program, stored procedures also pass back a return value. By default, this value is zero. If an error occurs during the execution of a stored procedure you may want to pass a value back to the calling environment that indicates the error that occurred. To do that you use the RETURN statement and the @@ERROR function.

The @@ERROR system function returns the error number that's generated by the execution of the most recent SQL statement. If the value is zero, it means that no error has occurred. The stored procedure listed below uses this function to test whether a DELETE statement that deletes a row from authors table is successful.

CREATE PROC spDeleteShashi @FirstName varchar(50) AS
DECLARE @ErrorVar int
SET @ErrorVar = @ERRORIF @ErrorVar <> 0        
   PRINT 'An Unknown Error Occurred'             
   RETURN @ErrorVar       

The RETURN statement immediately exists the procedure and returns an optional integer value to the calling environment. If you don't specify the value in this statement the return value is zero.


Similar Articles