Stored Procedures A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

Transact-SQL. 1. Declare float = 10 select * from customers where discnt
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Stored procedures Procedural programming in Microsoft SQL Server 1Stored procedures.
Module 9: Implementing Stored Procedures. Introduction to Stored Procedures Creating Executing Modifying Dropping Using Parameters in Stored Procedures.
Concepts of Database Management Sixth Edition
Database Management Fall 2003 Functions, Procedures and Triggers Chapter 10.
DAT702.  Standard Query Language  Ability to access and manipulate databases ◦ Retrieve data ◦ Insert, delete, update records ◦ Create and set permissions.
SQL Basics. SQL SQL (Structured Query Language) is a special-purpose programming language designed from managing data in relational database management.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Chapter 4 The Relational Model 3: Advanced Topics Concepts of Database Management Seventh Edition.
Stored Procedures A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and.
Views: Limiting Access to Data A view is a named select statement that is stored in a database as an object. It allows you to view a subset of rows or.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Defining Stored Procedures Named Collections of Transact-SQL Statements Encapsulate Repetitive Tasks Five Types (System, Local, Temporary, Remote, and.
Dinamic SQL & Cursor. Why Dinamic SQL ? Sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can.
Dexterity | CONFIDENTIAL 2009 MRO | Analytics | Insights 1 Stored Procedures.
Stored Procedures, Transactions, and Error-Handling
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
Triggers How triggers work Creating triggers Using triggers to maintain referential integrity Multirow considerations Nesting triggers Rules associated.
Module 9 Designing and Implementing Stored Procedures.
SQL/Lesson 4/Slide 1 of 45 Using Subqueries and Managing Databases Objectives In this lesson, you will learn to: *Use subqueries * Use subqueries with.
PL/SQL vs. Transact-SQL. Transact-SQL Central to the use of Microsoft® SQL Server™. All applications that communicate with SQL Server do so by sending.
Copyright © Curt Hill Stored Procedures In Transact-SQL.
Stored Procedure. Objective At the end of the session you will be able to know :  What are Stored Procedures?  Create a Stored Procedure  Execute a.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
Module 8: Implementing Stored Procedures. Overview Implementing Stored Procedures Creating Parameterized Stored Procedures Working With Execution Plans.
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
Slide 1 of 19Session 13 Ver. 1.0 Querying and Managing Data Using SQL Server 2005 In this session, you will learn to: Implement stored procedures Implement.
Working with SQL Server Database Objects Faculty: Nguyen Ngoc Tu.
G. Green 1.  Options include:  Script Files  already covered  APIs  last course topic  Database-Stored Code  our focus 2.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Slide 1 Chapter 7 – Part 3 Stored Procedure, Function &Trigger.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Introduction to Teradata Client Tools. 2 Introduction to Teradata SQL  OBJECTIVES :  Teradata Product Components.  Accessing Teradata – Database /
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
IT420: Database Management and Organization Triggers and Stored Procedures 24 February 2006 Adina Crăiniceanu
Table Structures and Indexing. The concept of indexing If you were asked to search for the name “Adam Wilbert” in a phonebook, you would go directly to.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
1 Stored Procedure, Function and Trigger. 2Objectives 1. Database Programming 2. Stored Procedure 3. Function 4. Trigger.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
Delete Data Database Administration Fundamentals LESSON 3.4.
1. Advanced SQL Functions Procedural Constructs Triggers.
Views / Session 3/ 1 of 40 Session 3 Module 5: Implementing Views Module 6: Managing Views.
1 Section 8 - Manipulating Data u The INSERT statement adds rows of data to the database u The UPDATE statement changes columns of existing data u The.
1 Section 3 - Select Statement u The Select statement allows you to... –Display Data –Specify Selection Criteria –Sort Data –Group Data for reporting –Use.
1 c6212 Advanced Database and Client Server MS SQL Server 2000 Stored Procedures and Parameters What ? Why ? How ?
1 Section 9 - Views, etc. u Part 1: Views u Part 2:Security Issues u Part 3:Transaction Management u Part 4:Set Operations u Part 5:Triggers and Stored.
Trigger used in PosgreSQL
TABLES AND INDEXES Ashima Wadhwa.
Instructor: Jason Carter
Chapter Name By Adrienne Watt
Stored Procedure, Function and Trigger
C1. SQL BAsic.
PRACTICE OVERVIEW PL/SQL Part - 1.
T-SQL Transact-SQL is microsoft implementation of SQL.
SQL Transactions 4/23/2019 See scm-intranet.
IST 318 Database Administration
Presentation transcript:

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

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)

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.

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.’