Download presentation
Presentation is loading. Please wait.
Published byJerome Ryan Modified over 9 years ago
1
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Stored Procedures in SQL Server Architecture Overview Designing and Creating SP SP Variables and Return Values Odds ‘n’ Ends
2
IMS 4212: Application Architecture and Intro to Stored Procedures 2 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
3
IMS 4212: Application Architecture and Intro to Stored Procedures 3 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
4
IMS 4212: Application Architecture and Intro to Stored Procedures 4 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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)
5
IMS 4212: Application Architecture and Intro to Stored Procedures 5 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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_Update GO 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 = @OrgID GO More on this SP later
6
IMS 4212: Application Architecture and Intro to Stored Procedures 6 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
7
IMS 4212: Application Architecture and Intro to Stored Procedures 7 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
8
IMS 4212: Application Architecture and Intro to Stored Procedures 8 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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 Manager
9
IMS 4212: Application Architecture and Intro to Stored Procedures 9 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
10
IMS 4212: Application Architecture and Intro to Stored Procedures 10 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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 types CREATE PROCEDURE up_Organization_Update @OrgID bigint, @OrgName varchar(50), @AcctName varchar(50), @WireAcct varchar(25) AS
11
IMS 4212: Application Architecture and Intro to Stored Procedures 11 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Creating SP (cont.) Body of procedure executes logic Parameters are used like variables in the SQL 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 = @OrgID GO
12
IMS 4212: Application Architecture and Intro to Stored Procedures 12 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
13
IMS 4212: Application Architecture and Intro to Stored Procedures 13 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu SP Variables & Return Values (cont.) CREATE PROCEDURE up_Organization_Insert @OrgName varchar(50), @AcctName varchar(50), @WireAcct varchar(25) AS DECLARE @OrgID bigint --Perform the insert INSERT INTO Organization ( OrgName, AcctName, WireAcct) VALUES (@OrgName, @AcctName, @WireAcct) --Load the PK into the return parameter SET @OrgID = @@Identity RETURN (@OrgID) GO Parameters Declare internal variable @@Identity gives identity attribute value of most recently added record Returning the variable value
14
IMS 4212: Application Architecture and Intro to Stored Procedures 14 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
15
IMS 4212: Application Architecture and Intro to Stored Procedures 15 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Testing SP Test SP in Enterprise Mgr. with the Exec statement Exec SP_Name [parameter list] [Parameter List] is a list of values, one for each parameter 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) AS DECLARE @OrgID bigint --Perform the insert INSERT INTO Organization ( OrgName, AcctName, WireAcct) VALUES (@OrgName, @AcctName, @WireAcct) --Load the PK into the return parameter SET @OrgID = @@Identity RETURN (@OrgID) GO
16
IMS 4212: Application Architecture and Intro to Stored Procedures 16 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
17
IMS 4212: Application Architecture and Intro to Stored Procedures 17 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
18
IMS 4212: Application Architecture and Intro to Stored Procedures 18 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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 Output AS --Decrement quantity on hand in Products table UPDATE Products SET UnitsInStock = UnitsInStock - @Quantity WHERE ProductID = @ProductID -- Return QOH After Update SET @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
19
IMS 4212: Application Architecture and Intro to Stored Procedures 19 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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 Output AS Declare @NewRec bit --Decrement quantity on hand in Products table UPDATE Products SET UnitsInStock = UnitsInStock - @Quantity WHERE ProductID = @ProductID -- Return QOH After Update SET @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) END ELSE BEGIN -- Update existing record UPDATE [Order Details] SET Quantity = Quantity + @Quantity WHERE OrderID = @OrderID AND ProductID = @ProductID END
20
IMS 4212: Application Architecture and Intro to Stored Procedures 20 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu User Defined Functions CREATE FUNCTION [dbo].[udf_Orders_LastCustOrderDate ] ( @CustomerID nchar(5) ) RETURNS datetime AS BEGIN -- Declare the return datetime variable DECLARE @LastOrderDate datetime -- Select the last date into the return variable SET @LastOrderDate = ( SELECT Max(OrderDate) FROM Orders WHERE CustomerID = @CustomerID) -- Return the result of the function RETURN @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(Cu stomerID) AS [Last Order] FROM Customers WHERE dbo.udf_Orders_LastCustOrderDate(Cu stomerID) < '1/1/2007'
21
IMS 4212: Application Architecture and Intro to Stored Procedures 21 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
22
IMS 4212: Application Architecture and Intro to Stored Procedures 22 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.