IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server Architecture Overview Designing and Creating SP SP Variables and Return Values Odds ‘n’ Ends
IMS 4212: Application Architecture and Intro to Stored Procedures 2 Dr. Lawrence West, Management Dept., University of Central Florida 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
IMS 4212: Application Architecture and Intro to Stored Procedures 3 Dr. Lawrence West, Management Dept., University of Central Florida 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
IMS 4212: Application Architecture and Intro to Stored Procedures 4 Dr. Lawrence West, Management Dept., University of Central Florida 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)
IMS 4212: Application Architecture and Intro to Stored Procedures 5 Dr. Lawrence West, Management Dept., University of Central Florida 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 varchar(25) AS UPDATE Organization SET OrgName AcctName WireAcct WHERE OrgID GO More on this SP later
IMS 4212: Application Architecture and Intro to Stored Procedures 6 Dr. Lawrence West, Management Dept., University of Central Florida 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
IMS 4212: Application Architecture and Intro to Stored Procedures 7 Dr. Lawrence West, Management Dept., University of Central Florida 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
IMS 4212: Application Architecture and Intro to Stored Procedures 8 Dr. Lawrence West, Management Dept., University of Central Florida 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
IMS 4212: Application Architecture and Intro to Stored Procedures 9 Dr. Lawrence West, Management Dept., University of Central Florida 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
IMS 4212: Application Architecture and Intro to Stored Procedures 10 Dr. Lawrence West, Management Dept., University of Central Florida 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 varchar(25) AS
IMS 4212: Application Architecture and Intro to Stored Procedures 11 Dr. Lawrence West, Management Dept., University of Central Florida 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 AcctName WireAcct WHERE OrgID GO
IMS 4212: Application Architecture and Intro to Stored Procedures 12 Dr. Lawrence West, Management Dept., University of Central Florida 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 syntax is not an input parameter it must be created with the DECLARE statement datatype Use SET to assign a value to a variable and are common intrinsic values that are returned
IMS 4212: Application Architecture and Intro to Stored Procedures 13 Dr. Lawrence West, Management Dept., University of Central Florida SP Variables & Return Values (cont.) CREATE PROCEDURE varchar(25) AS bigint --Perform the insert INSERT INTO Organization ( OrgName, AcctName, --Load the PK into the return parameter = RETURN GO Parameters Declare internal variable gives identity attribute value of most recently added record Returning the variable value
IMS 4212: Application Architecture and Intro to Stored Procedures 14 Dr. Lawrence West, Management Dept., University of Central Florida SP Variables & Return Values (cont.) Notes: –RETURN can only return a variable 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
IMS 4212: Application Architecture and Intro to Stored Procedures 15 Dr. Lawrence West, Management Dept., University of Central Florida 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 varchar(25) AS bigint --Perform the insert INSERT INTO Organization ( OrgName, AcctName, --Load the PK into the return parameter = RETURN GO
IMS 4212: Application Architecture and Intro to Stored Procedures 16 Dr. Lawrence West, Management Dept., University of Central Florida Testing SP (cont.) SP may also be tested with named parameters from an Enterprise Manager query window EXEC = = = = = 0
IMS 4212: Application Architecture and Intro to Stored Procedures 17 Dr. Lawrence West, Management Dept., University of Central Florida Default Parameter Values CREATE PROCEDURE smallint = real = 0 AS --Decrement QOH in Products table UPDATE Products SET UnitsInStock = UnitsInStock WHERE ProductID --Insert into [Order Details] INSERT INTO [Order @Discount) Execution need not provide values for all parameters (but may) EXEC = = = 14
IMS 4212: Application Architecture and Intro to Stored Procedures 18 Dr. Lawrence West, Management Dept., University of Central Florida Output Parameters Use Output param to return values ALTER PROCEDURE smallint = real = smallint Output AS --Decrement quantity on hand in Products table UPDATE Products SET UnitsInStock = UnitsInStock WHERE ProductID -- Return QOH After Update = ( SELECT UnitsInStock FROM Products WHERE ProductID Illustrating calling the procedure to the left from EM smallint EXEC = = = OUTPUT May also declare parameters in.VB code to be of ParameterDirection.Output
IMS 4212: Application Architecture and Intro to Stored Procedures 19 Dr. Lawrence West, Management Dept., University of Central Florida Flow Control with If [Else] ALTER PROCEDURE smallint = real = smallint Output AS bit --Decrement quantity on hand in Products table UPDATE Products SET UnitsInStock = UnitsInStock WHERE ProductID -- Return QOH After Update = ( SELECT UnitsInStock FROM Products WHERE ProductID = (SELECT Count(*) FROM [Order Details] WHERE OrderID AND ProductID = 0 BEGIN --Perform the insert into [Order Details] table INSERT INTO [Order @Discount) END ELSE BEGIN -- Update existing record UPDATE [Order Details] SET Quantity = Quantity WHERE OrderID AND ProductID END
IMS 4212: Application Architecture and Intro to Stored Procedures 20 Dr. Lawrence West, Management Dept., University of Central Florida User Defined Functions CREATE FUNCTION [dbo].[udf_Orders_LastCustOrderDate ] nchar(5) ) RETURNS datetime AS BEGIN -- Declare the return datetime variable datetime -- Select the last date into the return variable = ( SELECT Max(OrderDate) FROM Orders WHERE CustomerID -- Return the result of the function 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'
IMS 4212: Application Architecture and Intro to Stored Procedures 21 Dr. Lawrence West, Management Dept., University of Central Florida 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
IMS 4212: Application Architecture and Intro to Stored Procedures 22 Dr. Lawrence West, Management Dept., University of Central Florida 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