SQL Server Stored procedures


Published on

Published in: Education, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Stored Procedures 11/04/11
  • Stored Procedures 11/04/11
  • Stored Procedures 11/04/11
  • SQL Server Stored procedures

    1. 1. Stored Procedures CIS-282
    2. 2. Scripts v. Stored Procedures <ul><li>Script: Text file of SQL commands </li></ul><ul><li>Stored Procedure: SQL commands stored in database itself </li></ul><ul><ul><li>SPROC’s have more capabilities than a script </li></ul></ul>
    3. 3. BATCH <ul><li>Batch is a logical group of SQL statements </li></ul><ul><ul><li>Run-time error will halt execution only of FURTHER steps </li></ul></ul><ul><li>Can break up multiple steps using GO </li></ul><ul><ul><li>Not available in all tools </li></ul></ul><ul><ul><li>GO causes editing tool to send statements to that point for execution </li></ul></ul><ul><ul><li>GO isn’t sent to SQL Server </li></ul></ul>
    4. 4. Format of SPROC’s <ul><li>CREATE PROCEDURE <name> </li></ul><ul><li><parameter list> </li></ul><ul><li>AS </li></ul><ul><li><instructions to execute> </li></ul>
    5. 5. EXECUTE <ul><li>EXEC(cute) statement </li></ul><ul><ul><li>OR </li></ul></ul><ul><li>EXEC(cute) stored procedure name </li></ul><ul><li>Statement or sproc runs in it’s own scope </li></ul><ul><ul><li>Can’t ‘share’ variables directly </li></ul></ul><ul><ul><li>User’s security rules apply </li></ul></ul><ul><ul><li>Can’t be used in User Defined Function (UDF) </li></ul></ul>
    6. 6. Uses of Stored Procedures <ul><li>For returning data (select) </li></ul><ul><li>For editing data </li></ul><ul><li>For calculations </li></ul>
    7. 7. Parameters <ul><li>Method for sending data into and from a stored procedure </li></ul><ul><ul><li>INPUT parameters are values sent in </li></ul></ul><ul><ul><li>OUTPUT parameters are values returned </li></ul></ul><ul><ul><ul><li>Must have a holding space (variable) for the returned data </li></ul></ul></ul><ul><li>Defined before start of procedure (AS) </li></ul>
    8. 8. Declaring Parameters <ul><li>Include name and datatype </li></ul><ul><li>Default value is optional </li></ul><ul><ul><li>Without a default value, parameter is required </li></ul></ul><ul><li>Direction is optional (input is default) </li></ul><ul><ul><li>An output parameter must have direction specified </li></ul></ul>
    9. 9. Sample Input Parameter <ul><li>CREATE PROC upFindStudent </li></ul><ul><ul><li>@SID char(9) </li></ul></ul><ul><li>AS </li></ul><ul><ul><li>SELECT * </li></ul></ul><ul><ul><ul><li>FROM Students_T </li></ul></ul></ul><ul><ul><ul><ul><li>Where SchoolID=@SID </li></ul></ul></ul></ul>
    10. 10. Sample Output Parameter <ul><li>CREATE PROC upFindStudentID </li></ul><ul><ul><li>@First varchar(25), </li></ul></ul><ul><ul><li>@Last varchar(35), </li></ul></ul><ul><ul><li>@SID char(9) OUTPUT </li></ul></ul><ul><li>AS </li></ul><ul><ul><li>SELECT @SID=SchoolID </li></ul></ul><ul><ul><ul><li>FROM Students_T </li></ul></ul></ul><ul><ul><ul><ul><li>Where @First=Firstname and </li></ul></ul></ul></ul><ul><ul><ul><ul><li>@Last=Lastname </li></ul></ul></ul></ul>
    11. 11. Return Values <ul><li>Result of stored procedure indicates success or failure </li></ul><ul><li>Non-zero value indicates a problem </li></ul><ul><li>Must be an integer </li></ul><ul><li>Different from an output parameter </li></ul><ul><ul><li>Output parameter is about data </li></ul></ul><ul><li>RETURN <value> </li></ul><ul><ul><li>Causes immediate exit </li></ul></ul>
    12. 12. Variables <ul><li>Create using DECLARE </li></ul><ul><li>Need to start with ‘@’ </li></ul><ul><li>Can use SQL data types or custom data types </li></ul><ul><li>DECLARE @StudentName varchar(50) </li></ul>
    13. 13. Variable Assignment <ul><li>SET is usually used similar to procedural language </li></ul><ul><ul><li>SET @Var=value </li></ul></ul><ul><li>SELECT is usually used when getting a value from a query </li></ul><ul><ul><li>SELECT @Var=Sum(PossiblePoints) FROM Assignments </li></ul></ul>
    14. 14. Decision Making <ul><li>SQL supports two structures for branching: </li></ul><ul><ul><li>IF </li></ul></ul><ul><ul><li>CASE </li></ul></ul><ul><li>Both structures are similar to other languages (IF … THEN, SELECT CASE) </li></ul><ul><li>Both structures tend to have specific places where used </li></ul>
    15. 15. IF Blocks <ul><li>IF … ELSE </li></ul><ul><ul><li>No end if </li></ul></ul><ul><ul><li>Need to use Begin/End if have more than one instruction to execute </li></ul></ul><ul><li>IF StartDate < EndDate </li></ul><ul><ul><li>Begin </li></ul></ul><ul><ul><li>… </li></ul></ul><ul><ul><li>End </li></ul></ul><ul><li>ELSE </li></ul>
    16. 16. Simple Case Statement <ul><li>CASE </li></ul><ul><ul><li>Similar to SELECT CASE </li></ul></ul><ul><ul><li>Compares one value to different cases </li></ul></ul><ul><li>CASE Category </li></ul><ul><ul><li>WHEN ‘pop_comp’ THEN ‘Popular Computing’ </li></ul></ul><ul><ul><li>WHEN ‘mod_cook’ THEN ‘Modern Cooking’ </li></ul></ul><ul><li>END </li></ul>
    17. 17. Searched CASE <ul><li>No test expression </li></ul><ul><li>Each WHEN has a boolean test </li></ul><ul><li>CASE </li></ul><ul><ul><li>WHEN Points >= 90 THEN ‘A’ </li></ul></ul><ul><ul><li>WHEN Points < 90 AND Extra > 0 </li></ul></ul><ul><ul><ul><li>THEN ‘A’ </li></ul></ul></ul><ul><li>END </li></ul>
    18. 18. Looping (While) <ul><li>Typically used with a CURSOR </li></ul><ul><ul><li>Cursor data type allows a table to be stored in memory and each row/field to be accessed </li></ul></ul><ul><li>BREAK allows early exit from loop </li></ul><ul><li>CONTINUE forces control to start of loop </li></ul><ul><li>Working with sets is preferred over loops (SQL is about sets) </li></ul>
    19. 19. Finding Identity Values <ul><li>When need to find the value used to identify the last row added </li></ul><ul><li>@@Identity </li></ul><ul><li>Scope_Identity </li></ul><ul><li>Ident_Current </li></ul>
    20. 20. @@Identity – System Variable <ul><li>Returns the last identity value used as a result of INSERT or SELECT INTO </li></ul><ul><ul><li>Not limited to current scope; may not get correct value </li></ul></ul><ul><li>Returns Null if operation failed or a value wasn’t generated </li></ul><ul><li>Returns last number created if multiple inserts occur (i.e. SELECT INTO) </li></ul>
    21. 21. Scope_Identity() <ul><li>Return the last identity values generated in any table in the current session. </li></ul><ul><li>Returns values inserted only within the current scope </li></ul><ul><ul><li>Not affected by other operations. </li></ul></ul>
    22. 22. Ident_Current() <ul><li>Not limited by scope and session; </li></ul><ul><li>Limited to a specified table (table name specified as an argument value). </li></ul>
    23. 23. @@Rowcount – System Variables <ul><li>Number of rows returned or affected by the last statement </li></ul><ul><li>0 (zero) is often used as a logical test </li></ul><ul><ul><li>If no records found for where clause, notify system or process </li></ul></ul>
    24. 24. Errors <ul><li>Errors can occur because of SQL statement </li></ul><ul><ul><li>Invalid syntax, or data type </li></ul></ul><ul><li>Errors can also reflect business rules </li></ul><ul><ul><li>Data doesn’t match requirements </li></ul></ul>
    25. 25. @@Error – System Variable <ul><li>Determined after each SQL statement; </li></ul><ul><li>0 means statement was successful </li></ul><ul><li>Number other than zero is typically a specific error </li></ul><ul><li>Can store value in variable and test </li></ul>
    26. 26. Try/Catch <ul><li>Similar to .Net languages </li></ul><ul><li>Need to include BEGIN/END </li></ul><ul><ul><li>BEGIN TRY </li></ul></ul><ul><ul><ul><li><code> </li></ul></ul></ul><ul><ul><li>END TRY </li></ul></ul><ul><ul><li>BEGIN CATCH </li></ul></ul><ul><ul><ul><li><error handling code> </li></ul></ul></ul><ul><ul><li>END CATCH </li></ul></ul>
    27. 27. Raise Error <ul><li>Used to send information to calling program </li></ul><ul><li>Syntax: </li></ul><ul><li>RaisError (Message string OR Message ID, Severity, State) </li></ul><ul><ul><li>Severity – <14 information; 15-19 warning or user can correct; 20+ fatal </li></ul></ul><ul><ul><li>State – way to differentiate problems if needed; typically use 1 </li></ul></ul><ul><li>RAISERROR (50001,16,1) </li></ul>
    28. 28. Error Message <ul><li>Message ID or String </li></ul><ul><ul><li>Use ID if have custom or TSQL error to use </li></ul></ul><ul><ul><li>Use String for ‘on the fly’ message </li></ul></ul><ul><li>Stored Error Messages are server-specific </li></ul><ul><ul><li>Can add message </li></ul></ul><ul><ul><li>Number greater than 50000 </li></ul></ul>
    29. 29. Custom Error Messages <ul><li>Messages can include a parameter with % to allow addition to message </li></ul><ul><ul><li>‘ D’ – signed integer </li></ul></ul><ul><ul><li>‘ O’ – unsigned octal </li></ul></ul><ul><ul><li>‘ P’ – pointer </li></ul></ul><ul><ul><li>‘ S’ – string </li></ul></ul><ul><ul><li>‘ U’ – unsigned integer </li></ul></ul><ul><ul><li>‘ X’ or ‘x’ – unsigned hexadecimal </li></ul></ul>
    30. 30. Severity & State <ul><li>1 – 18: Informational </li></ul><ul><ul><li>11 – 16 typically raise error at client </li></ul></ul><ul><li>19 – 25: Severe error </li></ul><ul><ul><li>20+ is fatal error and connection will terminate </li></ul></ul><ul><li>State is ‘ad hoc’ and can help if same error happens in multiple places </li></ul><ul><ul><li>Range of 1 – 127 </li></ul></ul>
    31. 31. Sample Error Message <ul><li>RaisError(“Operation cannot be completed because field %s cannot be null”,1,1,”fieldname”) </li></ul>
    32. 32. Transactions <ul><li>Provides method for canceling an operation </li></ul><ul><li>Can restore rows, columns to original state in event of error or business logic failure </li></ul><ul><li>Use when changes will either be committed or discarded in entirety </li></ul>
    33. 33. ACID <ul><li>Atomicity : All of the changes will be accepted or none of the changes will be accepted </li></ul><ul><li>Consistency : Data is either in its original or changed state </li></ul><ul><li>Isolation : If multiple transactions occur, data is never available in an intermediate state </li></ul><ul><li>Durability : Once finished, all changes are complete and changes can only be done by another transaction/unit of work </li></ul>
    34. 34. Using A Transaction <ul><li>Begin Tran: Identifies the start </li></ul><ul><li>Commit Tran: Write changes </li></ul><ul><li>Rollback Tran: Cancel changes </li></ul><ul><li>Issue A Commit Or Rollback Or Connection Stays Open Until Terminated </li></ul>
    35. 35. Locking & Concurrency <ul><li>Locking allows a transaction to ensure that it can rollback </li></ul><ul><li>Prevents other operations from changing that data </li></ul><ul><li>Concurrency refers to multiple actions running against database at the same time </li></ul><ul><ul><li>What happens if you want to change data I’m working with? </li></ul></ul>
    36. 36. Sample Locking Levels <ul><li>Database </li></ul><ul><li>Table </li></ul><ul><li>Extent (memory) </li></ul><ul><li>Page (subset of extent) </li></ul><ul><li>Key </li></ul><ul><li>Row </li></ul>
    37. 37. Cursors <ul><li>Processing based on each row </li></ul><ul><ul><li>not set operations </li></ul></ul><ul><li>Declare @Cursor Cursor </li></ul><ul><li>Set @Cursor = Cursor For (select statement) </li></ul><ul><li>Open @Cursor </li></ul><ul><li>Fetch Next From @Cursor into (variables matching field list in select) </li></ul>
    38. 38. Using a Cursor <ul><li>Declare @Students Cursor </li></ul><ul><li>Set @Cursor = Cursor For (Select FirstName, LastName From Students) </li></ul><ul><li>Open @Students </li></ul><ul><li>While @@Fetch_Status = 0 Begin Fetch Next From @Students Into @First, @Last </li></ul><ul><li>Print @First + ‘ ‘+ @Last End </li></ul><ul><li>Close @Students </li></ul><ul><li>Deallocate @Students </li></ul>
    39. 39. @@Fetch_Status <ul><li>0 success; </li></ul><ul><li>-1 failed (read record outside recordset); </li></ul><ul><li>-2 missing record (eg. someone else deleted) </li></ul>