What Is A Stored Procedure
What Is A Stored Procedure
What Is A Stored Procedure
They are one or more SQL programs stored in a database as an executable object.
They can be called interactively, from within a client application or from another stored
procedure and from within triggers. We can pass parameters to and return from stored
procedures to increase their usefulness and flexibility. A stored procedure can return a
number or result set and a status code.
Big Question. When to use Stored Procedures: Stored procedures are well suited
for 2-tier environment, but the trend is shifting to 3-tier n more environments. In such
scenario business logic is often handled in some middle tier. So in such scenarios, we
would like to restrict the stored procedures to performing basic data-related tasks,
such as SELECT, UPDATE, DELETE.
For all examples shared below I have used Pubs database. You can download its msi
file from here and then attach .mdf file in your SQL Sever 2008.
http://www.microsoft.com/downloads/en/details.aspx?FamilyId=06616212-0356-
46A0-8DA2-EEBC53A68034&displaylang=en
Creating Stored Procedure:
We need to give the procedure a unique name within the schema and then write the
sequence of SQL statements to be executed within the procedure. Following is the
basic syntax for creating stored procedures:
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
-- Add the parameters for the stored procedure here
<@Param1, sysname, @p1> <Datatype_For_Param1, , int> =
<Default_Value_For_Param1, , 0>,
<@Param2, sysname, @p2> <Datatype_For_Param2, , int> =
<Default_Value_For_Param2, , 0>
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
This template contains parameters for parameter names, procedure name, author
name, create date, and so on. These template parameters are in the format
<parameter, type, value>:
1) It gives performance. When SET NOCOUNT is ON, the count (indicating the
number of rows affected by a Transact-SQL statement) is not returned.
2) When SET NOCOUNT is OFF, the count is returned. It eliminates the sending
of ONE_IN_PROC messages to the client for each statement in a stored
procedure.
3) For stored procedures that contain several statements that do not return
much actual data, this can provide a significant performance boost because
network traffic is greatly reduced. The setting of SET NOCOUNT is set at
execute or run time and not at parse time.
5. RETURN:
1) Return values indicate a return code from the stored procedure. The return
value does not have to be specified as the parameters do. We simply use the
RETURN SQL statement to return a value. This value has to be an Integer data
type and can return any value you need. For example, this value can be a
return code, the number of rows affected by a SQL statement, or the number of
rows in a table. Basically any integer data that you want to return can be
specified in a return value in your stored procedure.
(Using SSMS create new stored procedure and click CTRL + SHIFT + M, this will open a
box to comfortable provide parameter values)
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Vishal Nayan
-- Create date: 28-04-11
-- Description: Our first Sp
-- =============================================
CREATE PROCEDURE Author_Titles
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN
SELECT a.au_lname, a.au_fname, t.title
FROM titles t
INNER JOIN titleauthor ta ON t.title_id = ta.title_id
RIGHT OUTER JOIN authors a ON ta.au_id = a.au_id
RETURN 0
END
END
GO
You can also run stored procedures by selecting the sp and clicking Execute Stored
procedure. A window will open , since our above stored procedure does not tave any
input parameter, just click ok. A new query window will open with the below
statements;
USE [pubs]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[Author_Titles]
SELECT 'Return Value' = @return_value
GO
Ok, the query result is fine, but what return value is 0? Well even though we removed
the RETURN 0 statement from our stored procedure, the result were same.
Reason:
1. When used with a stored procedure, RETURN cannot return a null value. If a
procedure tries to return a null value (for example, using RETURN @status
when @status is NULL), a warning message is generated and a value of 0 is
returned.
2. One could say that no RETURN = RETURN NULL = RETURN 0. But no warning is
issued because you have not run RETURN NULL. And zero is expected because
it's a stored procedure.
Ok, the above stored procedure can also be written in better way. Below stored
procedure check whether any previous stored procedure with same name exists or not.
If yes, we drop and create new.
USE [pubs]
GO
GO
CREATE PROCEDURE [dbo].[Author_Titles]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN
SELECT a.au_lname, a.au_fname, t.title
FROM titles t
INNER JOIN titleauthor ta ON t.title_id = ta.title_id
RIGHT OUTER JOIN authors a ON ta.au_id = a.au_id
RETURN 0
END
END
GO
Execute it.
Result is below:
USE [pubs]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[reptq3]
@lolimit = 2,
@hilimit = 9,
@type = N'business'
SELECT 'Return Value' = @return_value
GO
Below is result
USE [pubs]
GO
/****** Object: StoredProcedure [dbo].[Author_Titles] Script Date: 04/29/2011
22:11:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Author_Titles] @state char(5)='%'
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN
SELECT a.au_lname, a.au_fname, t.title
FROM titles t
INNER JOIN titleauthor ta ON t.title_id = ta.title_id
RIGHT OUTER JOIN authors a ON ta.au_id = a.au_id
WHERE a.state like @state
RETURN 0
END
END
We can also make use of sp_help to know what all parameters are requried for Stored
procedure
B) How to pass Object names as parameter: In SQL Server 2008, if you pass an
object name as a parameter to a stored procedure, SQL Server attempts to treat it as
a table-valued parameter unless the object name is used either as an argument in a
WHERE clause or in a dynamic SQL query
As you can see, when the parameter is used in the FROM clause, SQL Server expects it
to be defined as a table variable.
To use the value in the parameter as a table name, you can build a dynamic SQL query
like below;
USE [pubs]
GO
/****** Object: StoredProcedure [dbo].[find_data] Script Date: 04/30/2011
19:34:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create proc [dbo].[find_data] @table varchar(128)
as
exec ('select * from ' + @table)
Let us create a stored procedure which will accept wild card say %
D) How to use table valued parameters: In previous versions of SQL Server, it was
not possible to share the contents of table variables between stored procedures. SQL
Server 2008 changes that with the introduction of table-valued parameters, which
allow you to pass table variables to stored procedures.
Points to remember:
After the table data type is created, we can use it for declaring local table variables
and for stored procedure parameters. To use the table-valued parameter in a
procedure, we create a procedure to receive and access data through a table-valued
parameter:
if OBJECT_ID('ab_parm_test') is not null
drop proc ab_parm_test
go
Then, when calling that stored procedure, we declare a local table variable using the
table data type defined previously, populate the table variable with data, and then
pass the table variable to the stored procedure:
Now we we got some data in our table type , we will execute our stored procedure.
1. SQL Server enables you to create private and global temporary stored
procedures.
Temporary stored procedures are analogous to temporary tables in that they
can be created with the # and ## prefixes added to the procedure name.
2. The # prefix denotes a local temporary stored procedure; ## denotes a global
temporary stored procedure
3. A local temporary stored procedure can be executed only by the connection that
created it, and
The procedure is automatically deleted when the connection is closed.
4. A global temporary stored procedure can be accessed by multiple connections
and exists until the connection used by the user who created the procedure is
closed and any currently executing versions
Of the procedure by any other connections are completed.
5. If a stored procedure not prefixed with # or ## is created directly in the temp
db database,
The stored procedure exists until SQL Server is shut down.
In SQL Server 2008, the object names that a stored procedure references do not have
to exist at the time the procedure is created. SQL Server 2008 checks for the existence
of database objects at the time the stored procedure is executed and returns an error
message at runtime if the referenced object doesn't exist. The only exception is when
a stored procedure references another stored procedure that doesn't exist. In that
case, a warning message is issued, but the stored procedure is still created
1. When a table or view does exist at procedure creation time, the column names
in the referenced
Table is validated. If a column name is mistyped or doesn't exist, the procedure
is not created
2. One advantage of delayed (or deferred) name resolution is the increased
flexibility when creating stored procedures; the order of creating procedures
and the tables they reference does not need to be exact.
3. Delayed name resolution is an especially useful feature when a stored
procedure references a temporary table that isn't created within that stored
procedure.
How to view Stored Procedure: we can view the source code for the stored
procedure in SQL server 2008 by querying the definition of the object catalog view
sys.sql_modules or by using the system procedure sp_helptext.
Example:
We can use ALTER statement to modify the stored procedure. This has two
advantages;
1. Here we don't have to drop the procedure first to make the changes, so it
remains available.
2. Because the stored procedure is not dropped, so we don't have to worry about
reassigning permission to it after modifying it.
So all we need is select a stored procedure and we have two ways to change stored
procedure.
Both option open stored procedure in a new window with ALTER keyword.
USE [pubs]
GO
/****** Object: StoredProcedure [dbo].[Author_Titles] Script Date: 04/29/2011
18:15:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Author_Titles]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN
SELECT a.au_lname, a.au_fname, t.title
FROM titles t
INNER JOIN titleauthor ta ON t.title_id = ta.title_id
RIGHT OUTER JOIN authors a ON ta.au_id = a.au_id
RETURN 0
END
END
If we want a procedure to be able to pass a parameter values out from the procedure,
we need to use the keyword OUTPUT when creating the procedure.
Ok, so let us create a stored procedure which accepts two parameters and one is the
output one.
Result is below:
------------------------------------
Sales this year until today's date: 111.
sp_who and sp_who2: Return information about current connections to SQL Server.
sp_help [object_name]: Lists the objects in a database or returns information about a
specified object.
sp_helpdb: Returns a list of databases or information about a specified database.
sp_configure: Lists or changes configuration settings.
sp_tables:Lists all tables available.
sp_ helpindex [table] - shows you index info (same info as sp_help)
sp_helpconstraint [table] - shows you primary/foreign key/defaults and other
constraints *
sp_depends [obj] - shows dependencies of an object, for example:
sp_depends [table] - shows you what stored procs, views, triggers, UDF affect this
table
sp_depends [sproc] - shows what tables etc are affected/used by this stored proc