stored procedures in sql server

22
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida [email protected] Stored Procedures in SQL Server Architecture Overview Designing and Creating SP SP Variables and Return Values Odds ‘n’ Ends

Upload: kimama

Post on 12-Jan-2016

199 views

Category:

Documents


12 download

DESCRIPTION

Stored Procedures in SQL Server. Architecture Overview Designing and Creating SP SP Variables and Return Values Odds ‘n’ Ends. Architecture Elements. A full-fledged systems production and operation environment will consist of a multitude of elements Databases Tables, relationships, indices - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

1Dr. Lawrence West, Management Dept., University of Central [email protected]

Stored Procedures in SQL Server

• Architecture Overview

• Designing and Creating SP

• SP Variables and Return Values

• Odds ‘n’ Ends

Page 2: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

2Dr. Lawrence West, Management Dept., University of Central [email protected]

Architecture Elements

• A full-fledged systems production and operation environment will consist of a multitude of elements

– Databases

• Tables, relationships, indices

• Stored procedures

– Database connectivity

• System connectivity (DSN, ADO.Net)

• Application connectivity

– Applications

Page 3: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

3Dr. Lawrence West, Management Dept., University of Central [email protected]

Architecture Elements (cont.)

• Next few weeks will be dealing with these elements

• It will be important that you understand individual topics in the context of this framework

DATABASE COMPONENTS

TABLES &RELATIONSHIPS

STOREDPROCEDURES

APPLICATIONSDATABASECONNECTIVITY

(ADO.Net)

Page 4: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

4Dr. Lawrence West, Management Dept., University of Central [email protected]

Stored Procedures

• Stored Procedures (SP) are procedural instructions stored within the database

• SP can be called accessed by other SP or by external applications

• Simplest SP execute a single SQL statement

• SP can be incredibly complex

• SP can accept variable values

• SP can return results

– Individual discrete values

– Entire recordsets (query results)

Page 5: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

5Dr. Lawrence West, Management Dept., University of Central [email protected]

Script to Create a Simple Stored Procedure

if exists (select name from sysobjects where name = 'up_Organization_Update' and type = 'P')drop procedure up_Organization_UpdateGO

CREATE PROCEDURE up_Organization_Update @OrgID bigint,@OrgName varchar(50),@AcctName varchar(50),@WireAcct varchar(25)AS UPDATE Organization SET OrgName = @OrgName, AcctName = @AcctName, WireAcct = @WireAcct WHERE OrgID = @OrgIDGO

More on this SPlater

Page 6: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

6Dr. Lawrence West, Management Dept., University of Central [email protected]

SP Advantages

• Centralized

– Any application can access the SP because it is stored with the database

– Maintenance takes place in one location

• Fast!!

– DB compiles SP and develops an ‘execution plan’ the first time the SP is run

– Subsequent runs are as fast as they can be

• Secure

– SP logic is hidden from anyone who does not have permissions to view the object

Really Important

Page 7: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

7Dr. Lawrence West, Management Dept., University of Central [email protected]

Designing SP

• Most tables will need INSERT INTO and UPDATE SP

• Identify other SP needed for your application’s business logic

– DELETE

– Specialized SELECT queries

• Retrieve an individual record by some criteria

• Retrieve a collection of records by a criteria

• Retrieve all records in a table

• Perform multi-table join queries

• Perform aggregate queries

Page 8: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

8Dr. Lawrence West, Management Dept., University of Central [email protected]

Designing SP (cont.)

• Naming Stored Procedures

– All begin with “up” for User Procedure

– Rest of name should give purpose of query

– Single table procedures should be “up_tablename_purpose”

– Examples

• up_customers_insert

• up_customers_selectbyCustID

• up_monthlysalesdetail_bymonth

SP appear alphabetically

in Enterprise M

anager

Page 9: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

9Dr. Lawrence West, Management Dept., University of Central [email protected]

Creating SP

• SP are created in Enterprise Manager

• Executing the SP creation command in the Query Analyzer creates the SP as an object in the DB

• SP can be modified in the Enterprise Manager or modified in the Query Analyzer and recreated

• Be sure to save your SP files from Query Analyzer so they can be modified and rerun if necessary

Demonstration

Page 10: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

10Dr. Lawrence West, Management Dept., University of Central [email protected]

Creating SP (cont.)

• CREATE PROCEDURE procedure_name[parameter list]AS

– Creates procedure

– Parameter names must start with ‘@’

– Parameters are typed with SQL Server data types

– Parameters should match field typesCREATE PROCEDURE up_Organization_Update @OrgID bigint,@OrgName varchar(50),@AcctName varchar(50),@WireAcct varchar(25)AS

Page 11: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

11Dr. Lawrence West, Management Dept., University of Central [email protected]

Creating SP (cont.)

• Body of procedureexecutes logic

• Parameters are usedlike variables in theSQL statements

• Note that there are no delimiters (single quotes for text or #-signs for dates) around these values

UPDATE Organization SET OrgName = @OrgName, AcctName = @AcctName, WireAcct = @WireAcct WHERE OrgID = @OrgIDGO

Page 12: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

12Dr. Lawrence West, Management Dept., University of Central [email protected]

SP Variables and Return Values

• When SP create a recordset with an SQL SELECT statement that recordset is available to the calling procedure or application (more later)

• SP may return a value with the RETURN(@varname) syntax

• If @varname is not an input parameter it must be created with the DECLARE statement DECLARE @varname datatype

• Use SET to assign a value to a variable

• @@ERROR and @@IDENTITY are common intrinsic values that are returned

Page 13: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

13Dr. Lawrence West, Management Dept., University of Central [email protected]

SP Variables & Return Values (cont.)

CREATE PROCEDURE up_Organization_Insert @OrgName varchar(50),@AcctName varchar(50),@WireAcct varchar(25)ASDECLARE @OrgID bigint

--Perform the insertINSERT INTO Organization ( OrgName, AcctName, WireAcct) VALUES (@OrgName, @AcctName, @WireAcct)

--Load the PK into the return parameterSET @OrgID = @@IdentityRETURN (@OrgID)

GO

Parameters

Declare internal variable

@@Identity gives identityattribute value of most recently added record

Returning the variable value

Page 14: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

14Dr. Lawrence West, Management Dept., University of Central [email protected]

SP Variables & Return Values (cont.)

• Notes:

– RETURN can only return a variable

• RETURN(@@Identity) won’t work

– Pay careful attention to data types

• When a parameter variable or internal variable interacts directly with a table field the field and the variable must be of the same data type

• Ensure that varchar variables and fields are the same length

– We will see how to read returned recordset values next time

Page 15: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

15Dr. Lawrence West, Management Dept., University of Central [email protected]

Testing SP

• Test SP in Enterprise Mgr.with the Exec statement

• Exec SP_Name [parameterlist]

• [Parameter List] is a listof values, one for eachparameter in the SP, in the specified order. Must have delimiters if applicable

• Enter in E.M.:– EXEC up_Organization_Insert ‘Test Org’, ‘Test

Acct’, ‘12345’– SELECT * FROM Organization

CREATE PROCEDURE up_Organization_Insert @OrgName varchar(50),@AcctName varchar(50),@WireAcct varchar(25)ASDECLARE @OrgID bigint

--Perform the insertINSERT INTO Organization ( OrgName, AcctName, WireAcct) VALUES (@OrgName, @AcctName, @WireAcct)

--Load the PK into the return parameterSET @OrgID = @@IdentityRETURN (@OrgID)

GO

Page 16: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

16Dr. Lawrence West, Management Dept., University of Central [email protected]

Testing SP (cont.)

• SP may also be tested with named parameters from an Enterprise Manager query window

EXEC [dbo].[up_Order_Details_Add_Test]@OrderID = 11096,@ProductID = 2,@UnitPrice = 14,@Quantity = 1,@Discount = 0

Page 17: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

17Dr. Lawrence West, Management Dept., University of Central [email protected]

Default Parameter Values

CREATE PROCEDURE [up_Order_Details_Add_Test]

@OrderID int,

@ProductID int,

@UnitPrice money,

@Quantity smallint = 1,

@Discount real = 0

AS

--Decrement QOH in Products table

UPDATE Products

SET UnitsInStock = UnitsInStock - @Quantity

WHERE ProductID = @ProductID

--Insert into [Order Details]

INSERT INTO [Order Details]

VALUES( @OrderID, @ProductID, @UnitPrice,

@Quantity, @Discount)

• Execution need not provide values for all parameters (but may)

EXEC [dbo].[up_Order_Details_Add_Test]@OrderID = 11096,@ProductID = 4,@UnitPrice = 14

Page 18: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

18Dr. Lawrence West, Management Dept., University of Central [email protected]

Output Parameters

• Use Output param to return values

ALTER PROCEDURE [up_Order_Details_Add_Test]

@OrderID int,@ProductID int,@UnitPrice money,@Quantity smallint = 1,@Discount real = 0,@QuantityOnHand smallint OutputAS --Decrement quantity on hand in

Products tableUPDATE ProductsSET UnitsInStock = UnitsInStock -

@QuantityWHERE ProductID = @ProductID

-- Return QOH After UpdateSET @QuantityOnHand = ( SELECT UnitsInStock FROM Products WHERE ProductID = @ProductID)

• Illustrating calling the procedure to the left from EM

• DECLARE @Qty smallint

EXEC [dbo].[up_Order_Details_Add_Test]@OrderID = 11096,@ProductID = 39,@UnitPrice = 14,@QuantityOnHand = @qty OUTPUT

SELECT @qty

• May also declare parameters in .VB code to be of ParameterDirection.Output

Page 19: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

19Dr. Lawrence West, Management Dept., University of Central [email protected]

Flow Control with If [Else]

ALTER PROCEDURE [up_Order_Details_Add_Test]

@OrderID int,@ProductID int,@UnitPrice money,@Quantity smallint = 1,@Discount real = 0,@QuantityOnHand smallint OutputAS

Declare @NewRec bit --Decrement quantity on hand in

Products tableUPDATE ProductsSET UnitsInStock = UnitsInStock -

@QuantityWHERE ProductID = @ProductID

-- Return QOH After UpdateSET @QuantityOnHand = ( SELECT UnitsInStock FROM Products WHERE ProductID = @ProductID)

set @NewRec = (SELECT Count(*) FROM [Order Details] WHERE OrderID = @OrderID AND ProductID = @ProductID)IF @NewRec = 0 BEGIN --Perform the insert into [Order

Details] table INSERT INTO [Order Details] VALUES( @OrderID, @ProductID,

@UnitPrice, @Quantity, @Discount) ENDELSE BEGIN -- Update existing record UPDATE [Order Details] SET Quantity = Quantity + @Quantity WHERE OrderID = @OrderID AND ProductID = @ProductID END

Page 20: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

20Dr. Lawrence West, Management Dept., University of Central [email protected]

User Defined Functions

CREATE FUNCTION [dbo].[udf_Orders_LastCustOrderDate]

(@CustomerID nchar(5)

) RETURNS datetimeASBEGIN

-- Declare the return datetime variableDECLARE @LastOrderDate datetime

-- Select the last date into the return variableSET @LastOrderDate = (

SELECT Max(OrderDate) FROM Orders WHERE CustomerID = @CustomerID)

-- Return the result of the functionRETURN @LastOrderDate

END

• Using the Function in a SP– Must use the dbo.function_name format– May have multiple parameters just like

a VB function

SELECT CustomerID, CompanyName,

dbo.udf_Orders_LastCustOrderDate(CustomerID) AS [Last Order]

FROM CustomersWHERE

dbo.udf_Orders_LastCustOrderDate(CustomerID) <

'1/1/2007'

Page 21: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

21Dr. Lawrence West, Management Dept., University of Central [email protected]

More on SP

• SP can actually be incredibly rich procedural code using T-SQL (transact SQL)

– Conditional execution

– Looping execution

– Branching execution

– Calling other SP (reusable logic modules)

• Oracle and other DB have similar capabilities

• Most common SP execute discrete DB activities based around SELECT, INSERT INTO, UPDATE, and DELETE statements

Page 22: Stored Procedures in SQL Server

IMS 4212: Application Architecture and Intro to Stored Procedures

22Dr. Lawrence West, Management Dept., University of Central [email protected]

More on SP (cont.)

• It is absolutely imperative that you practice these steps

– We are now moving into programming technologies

– You must be comfortable with each step

– You will be combining many elements in your applications (see figure on slide #3)

• Next:

– Using VB to connect to SQL Server using SP

– Working with recordsets created by a SP SELECT statement