stored procedures

39
Stored Procedures CIS-282

Upload: randy-riness-south-puget-sound-community-college

Post on 11-Jun-2015

910 views

Category:

Education


2 download

TRANSCRIPT

  • 1. CIS-282

2. Scripts v. Stored Procedures Script: Text file of SQL commands Stored Procedure: SQL commands stored in database itself SPROCs have more capabilities than a script 3. BATCH Batch is a logical group of SQL statements Run-time error will halt execution only of FURTHER steps Can break up multiple steps using GO Not available in all tools GO causes editing tool to send statements to that point for execution GO isnt sent to SQL Server 4. Format of SPROCs CREATE PROCEDURE AS 5. EXECUTE EXEC(cute) statement OR EXEC(cute) stored procedure name Statement or sproc runs in its own scope Cant share variables directly Users security rules apply Cant be used in User Defined Function (UDF) 6. Uses of Stored Procedures For returning data (select) For editing data For calculations 7. Parameters Method for sending data into and from a stored procedure INPUT parameters are values sent in OUTPUT parameters are values returned Must have a holding space (variable) for the returned data Defined before start of procedure (AS) 8. Declaring Parameters Include name and datatype Default value is optional Without a default value, parameter is required Direction is optional (input is default) An output parameter must have direction specified 9. Sample Input ParameterCREATE PROC upFindStudent @SID char(9)AS SELECT *FROM PersonsWhere SchoolID=@SID 10. Sample Output ParameterCREATE PROC upFindStudentID @First varchar(25), @Last varchar(35), @SID char(9) OUTPUTAS SELECT @SID=SchoolID FROM Students_T Where @First=Firstname and @Last=Lastname 11. Return Values Result of stored procedure indicates success or failure Non-zero value indicates a problem Must be an integer Different from an output parameter Output parameter is about data RETURN Causes immediate exit 12. Variables Create using DECLARE Need to start with @ Can use SQL data types or custom data typesDECLARE @StudentName varchar(50) 13. Variable Assignment SET is usually used similar to procedural language SET @Var=value SELECT is usually used when getting a value from a querySELECT @Var=Sum(PossiblePoints) FROM Assignments 14. Decision Making SQL supports two structures for branching: IF CASE Both structures are similar to other languages (IF THEN, SELECT CASE) Both structures tend to have specific places where used 15. IF Blocks IF ELSE No end if Need to use Begin/End if have more than one instruction to executeIF StartDate < EndDate Begin EndELSE 16. Simple Case Statement CASE Similar to SELECT CASE Compares one value to different casesCASE CategoryWHEN pop_comp THEN Popular ComputingWHEN mod_cook THEN Modern CookingEND 17. Searched CASE No test expression Each WHEN has a boolean testCASEWHEN Points >= 90 THEN AWHEN Points < 90 AND Extra > 0THEN AEND 18. Looping (While) Typically used with a CURSOR Cursor data type allows a table to be stored in memory and each row/field to be accessed BREAK allows early exit from loop CONTINUE forces control to start of loop Working with sets is preferred over loops (SQL isabout sets) 19. Finding Identity Values When need to find the value used to identify the lastrow added @@Identity Scope_Identity Ident_Current 20. @@Identity System variable, created/maintained automatically Returns the last identity value used as a result ofINSERT or SELECT INTO Not limited to current scope; may not get correct value Returns Null if operation failed or a value wasntgenerated Returns last number created if multiple inserts occur(i.e. SELECT INTO) 21. Scope_Identity() Return the last identity values generated in any tablein the current session. Returns values inserted only within the current scope Not affected by other operations. 22. Ident_Current() Not limited by scope and session; Limited to a specified table (table name specified as an argument value). 23. @@Rowcount System variable, created/maintained automatically Number of rows returned or affected by the laststatement 0 (zero) is often used as a logical test If no records found for where clause, notify system orprocess 24. Errors Errors can occur because of SQL statement Invalid syntax, or data type Errors can also reflect business rules Data doesnt match requirements 25. @@Error System variable, created/maintained automatically Value set after each SQL statement; 0 (zero) means statement was successful Number other than zero is typically a specific error Can store value in variable and test 26. Try/Catch Similar to .Net languages Need to include BEGIN/ENDBEGIN TRYEND TRYBEGIN CATCHEND CATCH 27. Raise Error Used to send information to calling program Syntax:RaisError (Message string OR Message ID, Severity, State) Severity