+ All Categories
Home > Documents > Stored Procedures

Stored Procedures

Date post: 02-Jan-2016
Category:
Upload: colorado-butler
View: 43 times
Download: 4 times
Share this document with a friend
Description:
Stored Procedures. A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and to increase performance. SQL Server also provides system procedures to perform administrative tasks and to update the system tables. - PowerPoint PPT Presentation
31
Stored Procedures • A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and to increase performance. • SQL Server also provides system procedures to perform administrative tasks and to update the system tables.
Transcript
Page 1: Stored Procedures

Stored Procedures

• A stored procedure is a named collection of SQL statements language.

• You can create stored procedures for commonly used functions and to increase performance.

• SQL Server also provides system procedures to perform administrative tasks and to update the system tables.

Page 2: Stored Procedures

How Stored Procedures Work

• When you run a stored procedure, Server prepares an execution plan so that the procedure’s execution is very fast. Stored procedures can:• Take parameters• Call other procedures• Return a status value to a calling procedure or batch to

indicate success or failure and the reason for failure• Return values of parameters to a calling procedure or

batch• Be executed on remote Servers

Page 3: Stored Procedures

How Stored Procedures Work

• The ability to write stored procedures greatly enhances the power, efficiency, and flexibility of SQL.

• Compiled procedures dramatically improve the performance of SQL statements and batches.

• In addition, stored procedures on other Servers can be executed if both your server and the remote server are set up to allow remote logins.

Page 4: Stored Procedures

How Stored Procedures Work

• Stored procedures differ from ordinary SQL statements and from batches of SQL statements in that they are precompiled.

• The first time you run a procedure, Server’s query processor analyzes it and prepares an execution plan that is ultimately stored in a system table.

• Subsequently, the procedure is executed according to the stored plan. Since most of the query processing work has already been performed, stored procedures execute almost instantly.

Page 5: Stored Procedures

Creating and Using Stored Procedures

• The syntax for creating a simple stored procedure, without special features such as parameters, is:

create procedure procedure_nameas SQL_statements

Sample:create procedure namelistas select name from sysusers

To execute the procedure• namelist• execute namelist• exec namelist

Page 6: Stored Procedures

Creating and Using Stored Procedures

To execute a stored procedure on a remote Server, you must give the server name. The full syntax for a remote procedure call is:execute server_name.[database_name].[owner].procedure_name

Page 7: Stored Procedures

Creating and Using Stored Procedures

A procedure can include more than one statement.create procedure showall asselect count(*) from sysusersselect count(*) from sysobjectsselect count(*) from syscolumnsWhen a create procedure command is successfully executed, the procedure’s name is stored in sysobjects, and its source text is stored in syscomments.You can display the source text of a procedure with sp_helptext:sp_helptext showall

Page 8: Stored Procedures

Stored Procedures and Performance

The queries used by stored procedures and triggers are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures and triggers may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.sp_recompile showall

Page 9: Stored Procedures

Creating and Using Stored Procedures

The complete syntax for create procedure is:create procedure [owner.]procedure_name[;number][(]@parameter_name

datatype [(length) | (precision [, scale ])][= default] [output]

[, @parameter_namedatatype [(length) | (precision [, scale])][= default] [output]]...[)]

[with recompile]

as {SQL_statements | external name dll_name}You can create a procedure in the current database only.

Page 10: Stored Procedures

Creating and Using Stored Procedures

Here is the complete syntax statement for execute:[exec[ute]] [@return_status = ]

[[[server.]database.]owner.]procedure_name[;number][[@parameter_name =] value |

[@parameter_name =] @variable [output][, [@parameter_name =] value |

[@parameter_name =] @variable [output]...]]

[with recompile]

Page 11: Stored Procedures

Creating and Using Stored Procedures

Example: Given an author’s last and first names, the procedure displays the names of any books written by that person and the name of each book’s publisher.create proc au_info @lastname varchar(40),

@firstname varchar(20) asselect au_lname, au_fname, title, pub_namefrom authors, titles, publishers, titleauthorwhere au_fname = @firstnameand au_lname = @lastnameand authors.au_id = titleauthor.au_idand titles.title_id = titleauthor.title_idand titles.pub_id = publishers.pub_idExecution:au_info Ringer, Anne

Page 12: Stored Procedures

Creating and Using Stored Procedures

Example: The following stored procedure queries the system tables. Given a table name as the parameter, the procedure displays the table name, index name, and index ID.create proc showind @table varchar(30) asselect table_name = sysobjects.name,index_name = sysindexes.name, index_id = indidfrom sysindexes, sysobjectswhere sysobjects.name = @tableand sysobjects.id = sysindexes.idExecution:execute showind titlesexec showind titlesexecute showind @table = titlesexecute GATEWAY.pubs2.dbo.showind titlesshowind titles or execute showind titles

Page 13: Stored Procedures

Creating and Using Stored ProceduresIf you supply the parameters in the form “@parameter = value” you can supply them in any order. Otherwise, you must supply parameters in the order of their create procedure statement. If you supply one value in the form “@parameter = value”, then supply all subsequent parameters this way.Below procedure displays the datatype of the qty column from the salesdetail table.create procedure showtype @tabname varchar(18), @colname varchar(18) asselect syscolumns.name, syscolumns.length,systypes.name from syscolumns, systypes, sysobjectswhere sysobjects.id = syscolumns.id and @tabname = sysobjects.name and @colname = syscolumns.name and syscolumns.type = systypes.type

Execution: exec showtype @colname = qty , @tabname = salesdetail

Page 14: Stored Procedures

Creating and Using Stored ProceduresYou can assign a default value for the parameter in the create procedure statement. This value, which can be any constant, is used as the argument to the procedure if the user does not supply one.Here is a procedure that displays the names of all the authors who have writtena book published by the publisher given as a parameter. If no publisher nameis supplied, the procedure shows the authors published by Algodata Infosystems.create proc pubinfo@pubname varchar(40) = "Algodata Infosystems" asselect au_lname, au_fname, pub_namefrom authors a, publishers p, titles t, titleauthor tawhere @pubname = p.pub_nameand a.au_id = ta.au_idand t.title_id = ta.title_idand t.pub_id = p.pub_id

exec pubinfo

Page 15: Stored Procedures

Creating and Using Stored ProceduresThis procedure, showind2, assigns “titles” as the default value for the @tableparameter:

create proc showind2@table varchar(30) = titles asselect table_name = sysobjects.name,index_name = sysindexes.name, index_id = indidfrom sysindexes, sysobjectswhere sysobjects.name = @tableand sysobjects.id = sysindexes.idThe column headings, for example, table_name, clarify the result display. Here is what showind2 shows for the authors table:showind2 authorsShowind2 Server uses the default, titles

Page 16: Stored Procedures

Creating and Using Stored ProceduresIn the create procedure statement, you can declare null as the default value for individual parameters:

create procedure showind3@table varchar(30) = null asif @table is null

print "Please give a table name."else

select table_name = sysobjects.name,index_name = sysindexes.name,index_id = indid

from sysindexes, sysobjectswhere sysobjects.name = @tableand sysobjects.id = sysindexes.id

The column headings, for example, table_name, clarify the result display. Here is what showind2 shows for the authors table:showind3 authorsShowind3

Page 17: Stored Procedures

Creating and Using Stored ProceduresUsing more than one parameter:

create proc au_info2@lastname varchar(30) = "D%",@firstname varchar(18) = "%" asselect au_lname, au_fname, title, pub_namefrom authors, titles, publishers, titleauthorwhere au_fname like @firstnameand au_lname like @lastnameand authors.au_id = titleauthor.au_idand titles.title_id = titleauthor.title_idand titles.pub_id = publishers.pub_idExecution:au_info2au_info2 Ringer

Page 18: Stored Procedures

Creating and Using Stored ProceduresProcedure groups:• The optional semicolon and integer number after the name of the

procedure in the create procedure and execute statements allow you to group procedures of the same name so that they can be dropped together with a single drop procedure statement.

• Procedures used in the same application are often grouped this way. For example, you might create a series of procedures called orders;1, orders;2, and so on. The following statement would drop the entire group:

drop proc orders• Once procedures have been grouped by appending a semicolon and

number to their names, they cannot be dropped individually. For example, the following statement is not allowed:

drop proc orders;2

Page 19: Stored Procedures

Creating and Using Stored ProceduresNesting procedures within procedures:Nesting occurs when one stored procedure or trigger calls another.You can call another procedure by name or by a variable name in place of the actual procedure name. For example:create procedure test1 @proc_name varchar(30)as exec @proc_name

Page 20: Stored Procedures

Creating and Using Stored ProceduresUsing temporary tables in stored procedures:You can create and use temporary tables in a stored procedure, but the temporary table exists only for the duration of the stored procedure that creates it. A single procedure can:• Create a temporary table• Insert, update, or delete data• Run queries on the temporary table• Call other procedures that reference

Page 21: Stored Procedures

Creating and Using Stored ProceduresUsing temporary tables in stored procedures:Since the temporary table must exist to create procedures that reference it, hereare the steps to follow:1. Create the temporary table using a create table statement or a select into statement. For example:

create table #tempstores(stor_id char(4), amount money)

2. Create the procedures that access the temporary table (but not the one that creates it).create procedure inv_amounts asselect stor_id, "Total Due" = sum(amount)from #tempstoresgroup by stor_id

3. Drop the temporary table:drop table #tempstores

4. Create the procedure that creates the table and calls the procedures created in step 2:create procedure inv_proc ascreate table #tempstores(stor_id char(4), amount money)

Page 22: Stored Procedures

Creating and Using Stored ProceduresUsing temporary tables in stored procedures:4. Create the procedure that creates the table and calls the procedures created in step 2:

create procedure inv_proc ascreate table #tempstores(stor_id char(4), amount money)insert #tempstoresselect sales.stor_id, sum(qty*(100-discount)/100*price)from sales, titles,discountswhere sales.title_id = titles.title_idgroup by sales.stor_id, sales.title_idexec inv_amounts

When you run the inv_proc procedure, it creates the table, but it only exists during the procedure’s execution. Try inserting values into the #tempstores table or running the inv_amounts procedure:You cannot, because the #tempstores table no longer exists.

Page 23: Stored Procedures

Returning information from stored procedures

Stored procedures can return the following types of information:• Return status – indicates whether or not the stored procedure completed successfully.• proc role function – checks whether the procedure was executed by a user with sa_role, sso_role, or ss_oper privileges.• Return parameters – report the parameter values back to the caller, who can then use conditional statements to check the returned value.

Page 24: Stored Procedures

Returning information from stored procedures

Return status: Stored procedures report a return status that indicates whether or not they completed successfully, and if they did not, the reasons for failure. This value can be stored in a variable when a procedure is called, and used in future Transact-SQL statements.Here is an example of a batch that uses the form of the execute statement that returns the status:declare @status intexecute @status = byroyalty 50select @status

Page 25: Stored Procedures

Returning information from stored procedures

Page 26: Stored Procedures

Returning information from stored procedures

User-generated return values: You can generate your own return values in stored procedures by adding a parameter to the return statement. You can use any integer outside the 0 through -99 range. The following example returns 1 when a book has a valid contract and returns 2 in all other cases:create proc checkcontract @titleid tidasif (select contract from authors where title_id = @titleid) = 1return 1elsereturn 2

Page 27: Stored Procedures

Returning information from stored procedures

The following stored procedure calls checkcontract, and uses conditionalclauses to check the return status:create proc get_au_stat @titleid tidasdeclare @retvalue intexecute @retvalue = checkcontract @titleidif (@retvalue = 1)print "Contract is valid."elseprint "There is not a valid contract."Here are the results when you execute get_au_stat with the title_id of a book with a valid contract:get_au_stat MC2222Contract is valid

Page 28: Stored Procedures

Returning information from stored proceduresReturn parameters: Another way that stored procedures can return information to the caller is through return parameters. The caller can then use conditional statements tocheck the returned value.This stored procedure performs multiplication on two integers (the thirdinteger, @result, is defined as an output parameter):create procedure mathtutor@mult1 int, @mult2 int, @result int outputasselect @result = @mult1 * @mult2To use mathtutor to figure a multiplication problem, you must declare the @result variable and include it in the execute statement. Adding the output keyword to the execute statement displays the value of the return parameters.declare @result intexec mathtutor 5, 6, @result outputselect @result

Page 29: Stored Procedures

Returning information from stored proceduresReturn parameters: This stored procedure checks to determine whether new book sales would cause an author’s royalty percentage to change (the @pc parameter is defined as an output parameter):

create proc roy_check @title tid, @newsales int, @pc int outputasdeclare @newtotal intselect @newtotal = (select titles.ytd_sales + @newsalesfrom titles where title_id = @title)select @pc = royalty from royschedwhere @newtotal >= roysched.lorange and @newtotal < roysched.hirange and roysched.title_id = @title

Page 30: Stored Procedures

Returning information from stored procedures

Return parameters: The following SQL batch calls the roy_check after assigning a value to the percent variable. The return parameters are printed before the next statement in the batch is executed:declare @percent intselect @percent = 10execute roy_check "BU1032", 1050, @pc = @percent outputselect Percent = @percent

Page 31: Stored Procedures

Returning information from stored proceduresReturn parameters: The following stored procedure calls roy_check and uses the return value for percent in a conditional clause:create proc newsales @title tid, @newsales intasdeclare @percent intdeclare @stor_pc intselect @percent = (select royalty from roysched, titleswhere roysched.title_id = @titleand ytd_sales >= roysched.lorangeand ytd_sales < roysched.hirangeand roysched.title_id = titles.title_id)select @stor_pc = @percentexecute roy_check @title, @newsales, @pc = @percentoutputif @stor_pc != @percentbeginprint "Royalty is changed."select @Percent = @percentendelse print ‘Royalty is the same.’


Recommended