Download presentation
Presentation is loading. Please wait.
Published byJunior Marsh Modified over 9 years ago
1
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.
2
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
3
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.
4
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.
5
Creating and Using Stored Procedures The syntax for creating a simple stored procedure, without special features such as parameters, is: create procedure procedure_name as SQL_statements Sample: create procedure namelist as select name from sysusers To execute the procedure namelist execute namelist exec namelist
6
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].proc edure_name
7
Creating and Using Stored Procedures A procedure can include more than one statement. create procedure showall as select count(*) from sysusers select count(*) from sysobjects select count(*) from syscolumns When 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
8
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
9
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_name datatype [(length) | (precision [, scale])] [= default] [output]]...[)] [with recompile] as {SQL_statements | external name dll_name} You can create a procedure in the current database only.
10
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]
11
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) as select au_lname, au_fname, title, pub_name from authors, titles, publishers, titleauthor where au_fname = @firstname and au_lname = @lastname and authors.au_id = titleauthor.au_id and titles.title_id = titleauthor.title_id and titles.pub_id = publishers.pub_id Execution: au_info Ringer, Anne
12
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) as select table_name = sysobjects.name, index_name = sysindexes.name, index_id = indid from sysindexes, sysobjects where sysobjects.name = @table and sysobjects.id = sysindexes.id Execution: execute showind titles exec showind titles execute showind @table = titles execute GATEWAY.pubs2.dbo.showind titles showind titles or execute showind titles
13
Creating and Using Stored Procedures If 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) as select syscolumns.name, syscolumns.length, systypes.name from syscolumns, systypes, sysobjects where sysobjects.id = syscolumns.id and @tabname = sysobjects.name and @colname = syscolumns.name and syscolumns.type = systypes.type Execution: exec showtype @colname = qty, @tabname = salesdetail
14
Creating and Using Stored Procedures You 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 written a book published by the publisher given as a parameter. If no publisher name is supplied, the procedure shows the authors published by Algodata Infosystems. create proc pubinfo @pubname varchar(40) = "Algodata Infosystems" as select au_lname, au_fname, pub_name from authors a, publishers p, titles t, titleauthor ta where @pubname = p.pub_name and a.au_id = ta.au_id and t.title_id = ta.title_id and t.pub_id = p.pub_id exec pubinfo
15
Creating and Using Stored Procedures This procedure, showind2, assigns “titles” as the default value for the @tableparameter: create proc showind2 @table varchar(30) = titles as select table_name = sysobjects.name, index_name = sysindexes.name, index_id = indid from sysindexes, sysobjects where sysobjects.name = @table and sysobjects.id = sysindexes.id The column headings, for example, table_name, clarify the result display. Here is what showind2 shows for the authors table: showind2 authors Showind2 Server uses the default, titles
16
Creating and Using Stored Procedures In the create procedure statement, you can declare null as the default value for individual parameters: create procedure showind3 @table varchar(30) = null as if @table is null print "Please give a table name." else select table_name = sysobjects.name, index_name = sysindexes.name, index_id = indid from sysindexes, sysobjects where sysobjects.name = @table and 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 authors Showind3
17
Creating and Using Stored Procedures Using more than one parameter: create proc au_info2 @lastname varchar(30) = "D%", @firstname varchar(18) = "%" as select au_lname, au_fname, title, pub_name from authors, titles, publishers, titleauthor where au_fname like @firstname and au_lname like @lastname and authors.au_id = titleauthor.au_id and titles.title_id = titleauthor.title_id and titles.pub_id = publishers.pub_id Execution: au_info2 au_info2 Ringer
18
Creating and Using Stored Procedures Procedure 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
19
Creating and Using Stored Procedures Nesting 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
20
Creating and Using Stored Procedures Using 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
21
Creating and Using Stored Procedures Using temporary tables in stored procedures: Since the temporary table must exist to create procedures that reference it, here are 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 as select stor_id, "Total Due" = sum(amount) from #tempstores group 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 as create table #tempstores (stor_id char(4), amount money)
22
Creating and Using Stored Procedures Using 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 as create table #tempstores (stor_id char(4), amount money) insert #tempstores select sales.stor_id, sum(qty*(100-discount)/100*price) from sales, titles,discounts where sales.title_id = titles.title_id group by sales.stor_id, sales.title_id exec 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.
23
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.
24
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 int execute @status = byroyalty 50 select @status
25
Returning information from stored procedures
26
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 tid as if (select contract from authors where title_id = @titleid) = 1 return 1 else return 2
27
Returning information from stored procedures The following stored procedure calls checkcontract, and uses conditional clauses to check the return status: create proc get_au_stat @titleid tid as declare @retvalue int execute @retvalue = checkcontract @titleid if (@retvalue = 1) print "Contract is valid." else print "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 MC2222 Contract is valid
28
Returning information from stored procedures Return parameters: Another way that stored procedures can return information to the caller is through return parameters. The caller can then use conditional statements to check the returned value. This stored procedure performs multiplication on two integers (the third integer, @result, is defined as an output parameter): create procedure mathtutor @mult1 int, @mult2 int, @result int output as select @result = @mult1 * @mult2 To 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 int exec mathtutor 5, 6, @result output select @result
29
Returning information from stored procedures Return 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 output as declare @newtotal int select @newtotal = (select titles.ytd_sales + @newsales from titles where title_id = @title) select @pc = royalty from roysched where @newtotal >= roysched.lorange and @newtotal < roysched.hirange and roysched.title_id = @title
30
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 int select @percent = 10 execute roy_check "BU1032", 1050, @pc = @percent output select Percent = @percent
31
Returning information from stored procedures Return 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 int as declare @percent int declare @stor_pc int select @percent = (select royalty from roysched, titles where roysched.title_id = @title and ytd_sales >= roysched.lorange and ytd_sales < roysched.hirange and roysched.title_id = titles.title_id) select @stor_pc = @percent execute roy_check @title, @newsales, @pc = @percent output if @stor_pc != @percent begin print "Royalty is changed." select @Percent = @percent end else print ‘Royalty is the same.’
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.