Stored Procedures and Functions Rose-Hulman Institute of Technology Curt Clifton.

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

What Is a User-defined Function? Scalar Functions –Similar to a built-in function Multi-Statement Table-valued Functions –Content like a stored procedure.
Index Blocking Factors, Views Rose-Hulman Institute of Technology Curt Clifton.
Chapter 4B: More Advanced PL/SQL Programming
Module 10: Implementing User-defined Functions. Overview What Is a User-defined Function? Defining Examples.
Module 9: Implementing Stored Procedures. Introduction to Stored Procedures Creating Executing Modifying Dropping Using Parameters in Stored Procedures.
Tools of the trade TSQL CIS 407. SQL Server Tools Books on line! Don’t use sql server authentication –Use windows authentication (safer) for developer.
Module 8: Implementing Views. Overview Introduction Advantages Definition Modifying Data Through Views Optimizing Performance by Using Views.
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
Stored Procedures A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Functions Lesson 10. Skills Matrix Function A function is a piece of code or routine that accepts parameters and stored as an object in SQL Server. The.
BIT275: Database Design (Fall 2015)
Stored Procedures A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and.
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.
TRAINING SESSIONS SQL Server Basics Design By.:.Net Prepared By:Dilip Namdeo Dated:23-Dec-09 Reference Site:
Stored Procedures, Transactions, and Error-Handling
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
Module 1: Introduction to Transact-SQL
Module 9 Designing and Implementing Stored Procedures.
T-SQL Transact-SQL is microsoft implementation of SQL. It contains additional programming constracts T-SQL enables you to write programs that contain SQL.
Module 9: Introduction to Programming Objects. Overview Displaying the Text of a Programming Object Introduction to Views Advantages of Views Creating.
5/24/01 Leveraging SQL Server 2000 in ColdFusion Applications December 9, 2003 Chris Lomvardias SRA International
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
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.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to SQL—Topics Introduction to.
Copyright © Curt Hill Stored Procedures In Transact-SQL.
Lecture 8 Creating Stored Functions. Objectives  After completing this lesson, you should be able to do the following:  What is Function?  Types of.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
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.
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
Module 7: Implementing Views. Overview Introducing Views Defining and Using Views Using Views to Optimize Performance.
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.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
G. Green 1.  Options include:  Script Files  already covered  APIs  last course topic  Database-Stored Code  our focus 2.
Creating Stored Procedures, Functions and Triggers Telerik Software Academy Databases.
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.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Ch 5. Introducing More Database Objects. Database Objects Table (ch2) View (ch3) Stored Procedure Trigger Function User-defined types.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Module 8: Using Programming Objects for Data Retrieval.
SQL Triggers, Functions & Stored Procedures Programming Operations.
1 Stored Procedure, Function and Trigger. 2Objectives 1. Database Programming 2. Stored Procedure 3. Function 4. Trigger.
In this session, you will learn to: Create and manage views Implement a full-text search Implement batches Objectives.
Module 9: Implementing Functions. Overview Creating and Using Functions Working with Functions Controlling Execution Context.
Module 9: Implementing User-Defined Functions. Overview Introducing User-Defined Functions Implementing User-Defined Functions.
Implementing Functions Advanced Database Dr. AlaaEddin Almabhouh.
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
Introduction to Structured Query Language (SQL) By Techandmate.comTechandmate.com Learn SQL Server With US.
Transact SQL (T-SQL) Creating Stored Procedures, Functions and Triggers SoftUni Team Technical Trainers Software University
User-defined functions, Procedures, Triggers and Transactions
Module T03d Software Engineering
A Guide to SQL, Seventh Edition
Task oriented processing
STORED PROCEDURES AND FUNCTION (9.6.1)
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Presentation transcript:

Stored Procedures and Functions Rose-Hulman Institute of Technology Curt Clifton

Outline  Stored Procedures or “Sprocs”  Functions  Statements Reference

Defining Stored Procedures  Named Collections of Transact-SQL Statements  Accept Input Parameters and Return Values  Return Status Value to Indicate Success or Failure  Encapsulate Repetitive Tasks

Advantages of Stored Procedures  Share Application Logic  Shield Database Schema Details  Provide Security Mechanisms  Improve Performance  Reduce Network Traffic

Entries into sysobjects and syscomments tables Compiled plan placed in procedure cache Compilation Optimization CreationCreation Execution (first time or recompile) Parsing Initial Processing of Sprocs

Execution Plan Retrieved Unused plan is aged out Execution PlanExecution Context SELECT * FROM dbo.member WHERE member_no = ? Connection Connection 2 Connection Subsequent Processing of Sprocs

USE Northwind GO CREATE PROC dbo.OverdueOrders AS SELECT * FROM dbo.Orders WHERE RequiredDate < GETDATE() AND ShippedDate IS Null GO Creating Stored Procedures  Create in Current Database Using the CREATE PROCEDURE (or CREATE PROC) Statement  Can Make Recursive Calls (but stack is limited)  Use sp_help to Display Information sp_help

EXEC OverdueOrders INSERT INTO Customers EXEC EmployeeCustomer Executing Stored Procedures  Executing a Stored Procedure by Itself  Executing a Stored Procedure Within an INSERT Statement

Guidelines for Creating Sprocs  dbo User Should Own All Stored Procedures E.g., dbo.OverdueOrders  One Stored Procedure for Each Task!  One Task for Each Stored Procedure!  Create, Test, and Troubleshoot  Avoid sp_ Prefix in Stored Procedure Names Used for system store procedures

USE Northwind GO ALTER PROC dbo.OverdueOrders AS SELECT CONVERT(char(8), RequiredDate, 1) RequiredDate, CONVERT(char(8), OrderDate, 1) OrderDate, OrderID, CustomerID, EmployeeID FROM Orders WHERE RequiredDate < GETDATE() AND ShippedDate IS Null ORDER BY RequiredDate GO USE Northwind GO ALTER PROC dbo.OverdueOrders AS SELECT CONVERT(char(8), RequiredDate, 1) RequiredDate, CONVERT(char(8), OrderDate, 1) OrderDate, OrderID, CustomerID, EmployeeID FROM Orders WHERE RequiredDate < GETDATE() AND ShippedDate IS Null ORDER BY RequiredDate GO Altering and Dropping Sprocs  Altering Stored Procedures  Check dependencies: sp_depends dbo.OverdueOrders  Dropping sprocs: DROP dbo.OverdueOrders

Using Parameters in Sprocs  Using Input Parameters  Executing Using Input Parameters  Returning Values Using Output Parameters

CREATE PROCEDURE dbo.[Year to Year DateTime AS IS NULL IS NULL BEGIN RAISERROR('NULL values are not allowed', 14, 1) RETURN END SELECT O.ShippedDate, O.OrderID, OS.Subtotal, DATENAME(yy,ShippedDate) AS Year FROM ORDERS O INNER JOIN [Order Subtotals] OS ON O.OrderID = OS.OrderID WHERE O.ShippedDate GO CREATE PROCEDURE dbo.[Year to Year DateTime AS IS NULL IS NULL BEGIN RAISERROR('NULL values are not allowed', 14, 1) RETURN END SELECT O.ShippedDate, O.OrderID, OS.Subtotal, DATENAME(yy,ShippedDate) AS Year FROM ORDERS O INNER JOIN [Order Subtotals] OS ON O.OrderID = OS.OrderID WHERE O.ShippedDate GO Using Input Parameters  Validate All Incoming Parameter Values First  Provide Default Values or Null Checks

EXEC AddCustomer 'ALFKI2', 'Alfreds Futterkiste', 'Maria Anders', 'Sales Representative', 'Obere Str. 57', 'Berlin', NULL, '12209', 'Germany', ' ' EXEC = = 'Maria = 'Alfreds = 'Sales = 'Obere Str. = = = = ' ' EXEC = = 'Maria = 'Alfreds = 'Sales = 'Obere Str. = = = = ' ' Executing Sprocs with Parms  By name:  By position:

Returning Values: Output Parms CREATE PROCEDURE smallint OUTPUT AS GO smallint EXECUTE MathTutor OUTPUT SELECT 'The result is: The result is: 30 CREATE PROCEDURE smallint OUTPUT AS GO smallint EXECUTE MathTutor OUTPUT SELECT 'The result is: The result is: 30 Results of Stored Procedure Procedure Executing Stored Procedure Procedure Creating Stored Procedure Procedure

Handling Error Messages  RETURN Statement Exits Query or Procedure Unconditionally  sp_addmessage Creates Custom Error Messages  Contains Error Number for Last Executed Statement  RAISERROR Statement Returns user-defined or system error message Sets system flag to record error

What Is a User-defined Function?  Scalar Functions (do not reference tables) Similar to a built-in function  Multi-Statement Table-valued Functions Content like a stored procedure Referenced like a view  In-Line Table-valued Functions Similar to a view with parameters Returns a table as the result of single SELECT statement

USE Northwind CREATE FUNCTION fn_NonNull nvarchar(30)) RETURNS nvarchar(30) BEGIN IS NULL = 'Not Applicable' END USE Northwind CREATE FUNCTION fn_NonNull nvarchar(30)) RETURNS nvarchar(30) BEGIN IS NULL = 'Not Applicable' END Creating a User-defined Function

ALTER FUNCTION dbo.fn_NewRegion ALTER FUNCTION dbo.fn_NewRegion DROP FUNCTION dbo.fn_NewRegion Altering and Dropping Functions  Altering Functions Retains assigned permissions Causes the new function definition to replace existing definition  Dropping Functions

Three Examples of Functions  Scalar User-defined Function  Multi-Statement Table-valued Function  In-Line Table-valued Function

Scalar User-defined Function  RETURNS Clause Specifies Data Type  Function Is Defined Within a BEGIN and END Block  Return Type Is Any Data Type Except text, ntext, image, cursor, or timestamp

Example SELECT dbo.fn_DateFormat(GETDATE(), ':')  Creating a function:  Calling the function: USE Northwind CREATE FUNCTION fn_DateFormat char(1)) RETURNS Nchar(20) AS BEGIN RETURN CONVERT(Nvarchar(20), + CONVERT(Nvarchar(20), + CONVERT(Nvarchar(20), END USE Northwind CREATE FUNCTION fn_DateFormat char(1)) RETURNS Nchar(20) AS BEGIN RETURN CONVERT(Nvarchar(20), + CONVERT(Nvarchar(20), + CONVERT(Nvarchar(20), END

Multi-Statement Table-valued Fn.  BEGIN and END Enclose Multiple Statements  RETURNS Clause Specifies table Data Type  RETURNS Clause Names and Defines the Table

USE Northwind GO CREATE FUNCTION fn_Employees nvarchar(9)) table (EmployeeID int PRIMARY KEY NOT NULL, [Employee Name] nvarchar(61) NOT NULL) AS BEGIN = 'ShortName' SELECT EmployeeID, LastName FROM Employees ELSE = 'LongName' SELECT EmployeeID, (FirstName + ' ' + LastName) FROM Employees RETURN END USE Northwind GO CREATE FUNCTION fn_Employees nvarchar(9)) table (EmployeeID int PRIMARY KEY NOT NULL, [Employee Name] nvarchar(61) NOT NULL) AS BEGIN = 'ShortName' SELECT EmployeeID, LastName FROM Employees ELSE = 'LongName' SELECT EmployeeID, (FirstName + ' ' + LastName) FROM Employees RETURN END SELECT * FROM dbo.fn_Employees('LongName') Or SELECT * FROM dbo.fn_Employees('ShortName') SELECT * FROM dbo.fn_Employees('LongName') Or SELECT * FROM dbo.fn_Employees('ShortName') Example  Creating the Function  Calling it:

In-Line Table-valued Function  Content of the Function Is a SELECT Statement  Do Not Use BEGIN and END  RETURN Specifies table as the Data Type  Format Is Defined by the Result Set

USE Northwind GO CREATE FUNCTION fn_CustomerNamesInRegion nvarchar(30) ) RETURNS table AS RETURN ( SELECT CustomerID, CompanyName FROM Northwind.dbo.Customers WHERE Region ) USE Northwind GO CREATE FUNCTION fn_CustomerNamesInRegion nvarchar(30) ) RETURNS table AS RETURN ( SELECT CustomerID, CompanyName FROM Northwind.dbo.Customers WHERE Region ) SELECT * FROM fn_CustomerNamesInRegion('WA') Example  Creating the Function  Calling it:

Types of Statements (1/2)  RETURN  DECLARE used to declare local variables  BEGIN... END Coalesce groups of statements Separate by semicolons Like { … } in Java, C, …

Types of Statements (2/2)  SET = ; Assignment  SELECT =, = … Multi-variable assignment  IF [ELSE ]  WHILE

Example: Assignment/Query  When right-hand side is single value: = (SELECT price FROM Sells WHERE rest = 'Joe''s' ANDsoda = 'Pepsi');

Multi-variable Assignment  Example: = = addr FROM Customer WHERE name = 'Rumi'

IF statements  Basic form: IF  Need BEGIN … END for multi-statement body: IF BEGIN ; ; END  Can use ELSE if needed: IF ELSE

WHILE Loops  Syntax: WHILE  Again, use BEGIN … END for longer body  Can be like “normal” while loops: WHILE (SELECT avg(price) FROM Sells) 5 BREAK END  Or use “cursors” to loop through query results

Cursor Example nvarchar(10); int; DECLARE NameCursor CURSOR LOCAL FOR SELECT LTRIM(RTRIM(username)) FROM [dbo].[Students] OPEN NameCursor FETCH NEXT FROM NameCursor WHILE = 0 BEGIN if ( 0 = (select count(*) from master.sys.syslogins where ) BEGIN EXEC('CREATE LOGIN ' + ' WITH PASSWORD=''' + '''') exec + 1 END else select + ' Already There') as result FETCH NEXT FROM NameCursor END

Remember CRUD!  Want interface code to easily manipulate data  Define stored procedures to: Create new entries in tables Retrieve data from tables Update entries in tables Delete entries from tables