ims 4212: application architecture and intro to stored procedures 1 dr. lawrence west, management...
TRANSCRIPT
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
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, ODBC, ADO.Net)
• Application connectivity
– Applications
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
(ODBC/ADO)
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 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)
– Output parameters (multiple discrete values)
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
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
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
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
• All business logic data access will take place in SP
• SP can contain any data manipulation queries
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
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 CREATE PROCEDURE command creates the SP as an object in the DB
• SP can be modified in the Enterprise Manager using ALTER PROCEDURE
• 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
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
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
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 statementDECLARE @varname datatype
• Use SET to assign a value to a variable
• @@ERROR and @@IDENTITY are common intrinsic values that are returned
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_Shippers_Insert @CompanyName nvarchar(40),@Phone nvarchar(24)ASDECLARE @ShipperID int
--Perform the insertINSERT INTO Shippers ( CompanyName, Phone) VALUES (@CompanyName, @Phone)
--Load the PK into the return parameterSET @ShipperID = @@IdentityRETURN (@ShipperID)
GO
Parameters
Declare internal variable
@@Identity gives identityattribute value of most recently added record
Returning the variable value
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 in SQL Server
2000 and earlier• RETURN(@@Identity) works SQL 2005 & later
– 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 a compatible 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
15Dr. 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
IMS 4212: Application Architecture and Intro to Stored Procedures
16Dr. Lawrence West, Management Dept., University of Central [email protected]
Exercises
• Create SP to:
– Return a list of CategoryID and CategoryName values sorted by name
– Receive a CategoryID and return all product details for products in that category
– Receive a country name and return all product details for products from that country
– Add a new Order Details recordHint: Be sure that you use valid OrderID and ProductID values
IMS 4212: Application Architecture and Intro to Stored Procedures
17Dr. Lawrence West, Management Dept., University of Central [email protected]
Alter Procedure
• You may also update a stored procedure using the ALTER PROCEDURE procedure_name syntax
– Right click procedure name in Query Analyzer Object Browser
– Select Modify from menu
IMS 4212: Application Architecture and Intro to Stored Procedures
18Dr. Lawrence West, Management Dept., University of Central [email protected]
Alter Procedure (cont.)
SET QUOTED_IDENTIFIER ON GOSET ANSI_NULLS ON GO
ALTER PROCEDURE up_Region_Insert@RegionID int,@RegionDescription nchar(50)AS
INSERT INTO Region (RegionID, RegionDescription)VALUES (@RegionID, @RegionDescription)
GOSET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS ON GO
Added by editor
IMS 4212: Application Architecture and Intro to Stored Procedures
19Dr. Lawrence West, Management Dept., University of Central [email protected]
Commenting SPs
/* up_Shippers_Add** Receives input parameters for the two non-identity attributes of* the shippers table and adds a new shippers record* Retrieves the value of the newly created record PK and* returns it as the return value of the SP*/
• Comment purpose of SP at top
• Use /*… */ to create a block comment
• -- at beginning of a line creates a comment on the line
IMS 4212: Application Architecture and Intro to Stored Procedures
20Dr. Lawrence West, Management Dept., University of Central [email protected]
Default Parameter Values
• A value must be provided for every parameter
– But a parameter need not be provided for every field
• A default value can be provided in the SP which will be used if the calling application does not provide one
• All of the following are legal:CREATE PROCEDURE up_ProcedureName@CompanyName nvarchar(40),@OrderDate = GetDate(),@EmployeeID = 0,@ShippedDate = NULLAS
Value must be providedWill use current date if no valWill use zero if no valueNeed not receive a value and will enter NULL if none provided
IMS 4212: Application Architecture and Intro to Stored Procedures
21Dr. Lawrence West, Management Dept., University of Central [email protected]
Testing SP From Query Analyzer
DELETE Shippers WHERE CompanyName = 'Test Co'
--Testing by adding values in list in parameter orderEXEC up_Shippers_Add 'Test Co', '555-1212'GO
--Testing by providing named parameter valuesEXEC up_Shippers_Add @CompanyName = 'Test Co', @Phone = 'Explicit'GO
--Testing by adding named parameter values reversedEXEC up_Shippers_Add @Phone = 'Reverse', @CompanyName = 'Test Co'
--Testing by providing no phone number with default providedEXEC up_Shippers_Add 'Test Co'
SELECT * FROM Shippers
IMS 4212: Application Architecture and Intro to Stored Procedures
22Dr. Lawrence West, Management Dept., University of Central [email protected]
What’s To Come
• The Stored Procedures we will build here can easily be invoked from our Visual Basic programs
• Syntax is a little complex but is always the same for the same kind of SP
• Learn VB syntax (mimic the example code) and the applications are straightforward to implement