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.
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
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.
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.
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
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
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
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
Creating and Using Stored Procedures The complete syntax for create procedure is: create procedure [owner.]procedure_name[;number] datatype [(length) | (precision [, scale ])] [= default] [output] 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.
Creating and Using Stored Procedures Here is the complete syntax statement for execute: [ exec[ute]] = ] [[[server.]database.]owner.]procedure_name[;number] =] value | [output] [, =] value | [output]...]] [with recompile]
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 varchar(20) as select au_lname, au_fname, title, pub_name from authors, titles, publishers, titleauthor where au_fname and au_lname 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
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 varchar(30) as select table_name = sysobjects.name, index_name = sysindexes.name, index_id = indid from sysindexes, sysobjects where sysobjects.name and sysobjects.id = sysindexes.id Execution: execute showind titles exec showind titles execute = titles execute GATEWAY.pubs2.dbo.showind titles showind titles or execute showind titles
Creating and Using Stored Procedures If you supply the parameters in the form = 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 = value”, then supply all subsequent parameters this way. Below procedure displays the datatype of the qty column from the salesdetail table. create procedure varchar(18) as select syscolumns.name, syscolumns.length, systypes.name from syscolumns, systypes, sysobjects where sysobjects.id = syscolumns.id = sysobjects.name = syscolumns.name and syscolumns.type = systypes.type Execution: exec = = salesdetail
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 varchar(40) = "Algodata Infosystems" as select au_lname, au_fname, pub_name from authors a, publishers p, titles t, titleauthor ta = 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
Creating and Using Stored Procedures This procedure, showind2, assigns “titles” as the default value for create proc varchar(30) = titles as select table_name = sysobjects.name, index_name = sysindexes.name, index_id = indid from sysindexes, sysobjects where sysobjects.name 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
Creating and Using Stored Procedures In the create procedure statement, you can declare null as the default value for individual parameters: create procedure varchar(30) = null as 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 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
Creating and Using Stored Procedures Using more than one parameter: create proc varchar(30) = varchar(18) = "%" as select au_lname, au_fname, title, pub_name from authors, titles, publishers, titleauthor where au_fname and au_lname 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
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
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 varchar(30) as
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
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.
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: int = byroyalty 50
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 tid as if (select contract from authors where title_id = 1 return 1 else return 2
Returning information from stored procedures The following stored procedure calls checkcontract, and uses conditional clauses to check the return status: create proc tid as int = if = 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
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 is defined as an output parameter): create procedure int output as To use mathtutor to figure a multiplication problem, you must declare variable and include it in the execute statement. Adding the output keyword to the execute statement displays the value of the return parameters. int exec mathtutor 5, output
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 parameter is defined as an output parameter): create proc int output as int = (select titles.ytd_sales from titles where title_id = royalty from roysched >= roysched.lorange < roysched.hirange and roysched.title_id
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: int = 10 execute roy_check "BU1032", output select Percent
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 int as int int = (select royalty from roysched, titles where roysched.title_id and ytd_sales >= roysched.lorange and ytd_sales < roysched.hirange and roysched.title_id = titles.title_id) @pc output begin print "Royalty is changed." end else print ‘Royalty is the same.’