Introduction To SQL Unit 14 Modern Business Technology Introduction To TSQL Unit 14 Developed by Michael Hotek
Batches <ul><li>Previously we can discussed batches of SQL statements </li></ul><ul><li>A brief review: </li></ul><ul><ul>...
<ul><li>So, what does this have to do with stored procedures </li></ul><ul><li>A stored procedure is a batch of SQL statem...
Stored Procedures <ul><li>A stored procedure is a collection of SQL statements that are stored under a name and executed <...
Steps to Execution <ul><li>When a SQL statement is executed, many things happen on the server </li></ul><ul><ul><li>Parsin...
Stored Procedures <ul><li>When you create a stored procedure all of the steps of parsing, checking, compiling, etc. are ca...
Stored Procedures <ul><li>The first time a stored procedure is executed, a query plan is built and stored </li></ul><ul><l...
Benefits <ul><li>Execute faster than the same set of commands run as a batch </li></ul><ul><ul><li>The code is already com...
Creating <ul><li>To create a stored procedure, you issue the create procedure command </li></ul><ul><li>create procedure p...
Guidelines <ul><li>Manage the source code of your stored procs the same as you would any other code in the development pro...
Valid Statements <ul><li>Just about any SQL statement can be included in a stored procedure except: </li></ul><ul><ul><li>...
Naming <ul><li>One little known fact for SQL Server (Sybase and MS) is that any procedure named sp_… is treated as a syste...
Executing <ul><li>To execute a stored procedure, the user issues an execute proc command </li></ul><ul><li>execute proc_na...
Stored Procedures <ul><li>To view the source code for a stored procedure, you would use the sp_helptext (or the equivalent...
Input Parameters <ul><li>Stored procedures can accept input parameters.  (Most procs are constructed this way.) </li></ul>...
Input Parameters <ul><li>create procedure proc_name </li></ul><ul><li>(@parameter  datatype </li></ul><ul><li>[,@parameter...
Input Parameters <ul><li>Parameter names can be up to 30 characters including the @ </li></ul><ul><li>There can be up to 2...
Executing Procedures <ul><li>A procedure with parameters can be executed two ways: </li></ul><ul><ul><li>by name </li></ul...
Multiple Parameters <ul><li>You can define more than one parameter for a stored procedure </li></ul><ul><li>create proc my...
Default Value <ul><li>You do not have to always pass the same number of arguments that have been defined in the procedure ...
Default Values <ul><li>When executing a procedure, you must pass values for all parameters that do not have defaults assig...
Common Errors <ul><li>Values are not compatible with the defined datatype </li></ul><ul><li>Parameters are passed via mixe...
Stored Procedures <ul><li>Sometimes we need to return values from a stored procedure </li></ul><ul><li>This is accomplishe...
Error Handling <ul><li>You should always implement error handling in your stored procedures </li></ul><ul><li>This include...
Output Values <ul><li>create procedure myproc </li></ul><ul><li>(@book_id  char(6),  </li></ul><ul><li>@total_sales  int o...
Return Status <ul><li>Every procedure will return a status </li></ul><ul><ul><li>0 for successful completion </li></ul></u...
Comments <ul><li>Add comments to document functionality </li></ul><ul><li>Establish standards to promote consistency </li>...
Comments <ul><li>Suggestions con't: </li></ul><ul><ul><li>Include all comments after the as statement </li></ul></ul><ul><...
Transaction Control <ul><li>Establish a transaction mode (chained or unchained) for your application -- Sybase only </li><...
@@trancount <ul><li>@@trancount contains the nesting level of transaction </li></ul><ul><li>Each begin tran increments the...
Nested Procedures <ul><li>You can nest procedures (have one procedure that calls another) up to 16 levels deep </li></ul><...
Nesting <ul><li>A stored procedure containing a transaction can contain another procedure containing a transaction </li></...
Nesting and Savepoints <ul><li>Nested transactions that contain savepoints, if rolled back, will not cause the outermost t...
Server Cursors <ul><li>Server cursors are cursors that execute within a stored procedure </li></ul><ul><li>They are declar...
Cursor Scope <ul><li>A stored procedure can access the cursors that are declared outside the procedure or in other procedu...
Standards <ul><li>Add defaults to all input arguments </li></ul><ul><li>Check for missing arguments and print a usage stat...
Restrictions <ul><li>Some SQL statements can not be used </li></ul><ul><li>Create tables before you refer to them </li></u...
Notes <ul><li>Stored procedures can reference objects in another database </li></ul><ul><li>Temporary tables created in a ...
Dependencies <ul><li>Stored procedures operate on one or more objects in a database(s) </li></ul><ul><li>Use the sp_depend...
Recompile <ul><li>A query plan is created the first time a procedure is executed </li></ul><ul><li>Sometimes, the query pl...
Recompile <ul><li>Use the with recompile only when there is no way to predict the best query plan at compile time </li></u...
Unit 14 Review <ul><li>A stored procedure is a batch of SQL that is compiled and stored in a database </li></ul><ul><li>So...
Unit 14 Exercises <ul><li>Time allotted for exercises is 1 hour </li></ul>
Upcoming SlideShare
Loading in …5
×

Intro to tsql

436
-1

Published on

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
436
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Intro to tsql

  1. 1. Introduction To SQL Unit 14 Modern Business Technology Introduction To TSQL Unit 14 Developed by Michael Hotek
  2. 2. Batches <ul><li>Previously we can discussed batches of SQL statements </li></ul><ul><li>A brief review: </li></ul><ul><ul><li>A batch is one or more SQL statements </li></ul></ul><ul><ul><li>If one statement in a batch is invalid, the entire batch is rejected </li></ul></ul><ul><ul><li>An object can not be created, dropped, and recreated in a batch </li></ul></ul>
  3. 3. <ul><li>So, what does this have to do with stored procedures </li></ul><ul><li>A stored procedure is a batch of SQL statements </li></ul><ul><li>The only difference is that a batch is compiled at the time of execution and a stored procedure is already compiled </li></ul>Stored Procedures
  4. 4. Stored Procedures <ul><li>A stored procedure is a collection of SQL statements that are stored under a name and executed </li></ul><ul><li>Allow many users to execute the same code </li></ul><ul><li>Provide a centralized and consistent implementation of code </li></ul><ul><li>Commonly used by </li></ul><ul><ul><li>Frequently used queries </li></ul></ul><ul><ul><li>Business logic </li></ul></ul><ul><ul><li>Error handling routines </li></ul></ul><ul><ul><li>Repetitive administrative functions </li></ul></ul>
  5. 5. Steps to Execution <ul><li>When a SQL statement is executed, many things happen on the server </li></ul><ul><ul><li>Parsing - the statement is parsed into a format SQL Server can handle for efficient operation </li></ul></ul><ul><ul><li>Syntax checking - During the parsing stage, the SQL is also checked for any syntax errors </li></ul></ul><ul><ul><li>Resolution - all objects are resolved to their internal representations (IDs) </li></ul></ul><ul><ul><li>Compile - The statement is compiled into machine language the server can execute </li></ul></ul><ul><ul><li>Query plan - A plan for executing the query is determined for the fastest access to data </li></ul></ul><ul><li>All of this happens rather quickly on the server and is required for every statement you execute </li></ul>
  6. 6. Stored Procedures <ul><li>When you create a stored procedure all of the steps of parsing, checking, compiling, etc. are carried out </li></ul><ul><li>When the user executes the stored procedure none of these steps need to be performed </li></ul><ul><li>This is what makes stored procedures execute more quickly than batches </li></ul>
  7. 7. Stored Procedures <ul><li>The first time a stored procedure is executed, a query plan is built and stored </li></ul><ul><li>This query plan is determined by any arguments passed to the proc the first time and statistics SQL Server keeps </li></ul><ul><li>After the first execution, the stored query plan is used an does not need to be rebuilt </li></ul><ul><li>A stored procedure is not a shared object. Each concurrent user receives their own copy. </li></ul><ul><ul><li>If two users simultaneously execute a stored procedure, there will actually be two copies of the object executing (one for each user) </li></ul></ul>
  8. 8. Benefits <ul><li>Execute faster than the same set of commands run as a batch </li></ul><ul><ul><li>The code is already compiled </li></ul></ul><ul><ul><li>No query plan needs to be created </li></ul></ul><ul><ul><li>The code generally resides in memory </li></ul></ul><ul><li>Reduce network traffic </li></ul><ul><ul><li>You are sending an exec proc command instead if the entire batch of SQL across the network </li></ul></ul><ul><li>Enforce consistency </li></ul><ul><ul><li>Commands are executed the same </li></ul></ul><ul><ul><li>Error handling is standardized </li></ul></ul><ul><li>Provide security </li></ul><ul><ul><li>Users can be given execution permission on a stored procedure that modifies data instead of permission to directly modify the table </li></ul></ul><ul><li>Modular design </li></ul>
  9. 9. Creating <ul><li>To create a stored procedure, you issue the create procedure command </li></ul><ul><li>create procedure proc_name </li></ul><ul><li>as </li></ul><ul><ul><li>SQL statement or batch </li></ul></ul><ul><li>return </li></ul><ul><li>The stored procedure is stored in the current database, but it can access objects in other databases </li></ul><ul><li>The create procedure command can not be combined with any other statements in a single batch </li></ul>
  10. 10. Guidelines <ul><li>Manage the source code of your stored procs the same as you would any other code in the development process </li></ul><ul><li>Even though the DBMS will return at the end of a proc, always end a procedure with the return statement </li></ul><ul><li>Develop naming, commenting, and documentation standards for all of your stored procedures. </li></ul><ul><ul><li>Makes procedures more readable </li></ul></ul><ul><ul><li>Simplifies identification of procedures </li></ul></ul><ul><ul><li>Reduces the administrative overhead </li></ul></ul>
  11. 11. Valid Statements <ul><li>Just about any SQL statement can be included in a stored procedure except: </li></ul><ul><ul><li>create view </li></ul></ul><ul><ul><li>create rule </li></ul></ul><ul><ul><li>create default </li></ul></ul><ul><ul><li>create procedure </li></ul></ul><ul><ul><li>create trigger </li></ul></ul><ul><ul><li>use </li></ul></ul><ul><li>Not being able to issue a use can be at times be limiting, so be careful to plan where the stored procedures are located </li></ul>
  12. 12. Naming <ul><li>One little known fact for SQL Server (Sybase and MS) is that any procedure named sp_… is treated as a system stored procedure and can be executed with a database different than the one created in </li></ul><ul><li>You can cause the stored procedure to execute in the context of another database simply be preceding it with a database name </li></ul><ul><li>(exec pubs..sp_test) </li></ul>
  13. 13. Executing <ul><li>To execute a stored procedure, the user issues an execute proc command </li></ul><ul><li>execute proc_name or exec proc_name </li></ul><ul><li>You can leave off the exec if the statement is the first statement in a batch, but this is very poor programming </li></ul><ul><li>Procedures can be called from: </li></ul><ul><ul><li>Batches </li></ul></ul><ul><ul><li>Other stored procedures </li></ul></ul><ul><ul><li>Triggers </li></ul></ul><ul><ul><li>Other programs </li></ul></ul>
  14. 14. Stored Procedures <ul><li>To view the source code for a stored procedure, you would use the sp_helptext (or the equivalent) stored procedure </li></ul><ul><ul><li>exec sp_helptext myproc </li></ul></ul><ul><li>You can rename a procedure with sp_rename </li></ul><ul><ul><li>exec sp_rename myproc sp_myproc </li></ul></ul><ul><li>To delete (drop) a procedure, issue the drop procedure command </li></ul><ul><ul><li>drop procedure myproc </li></ul></ul><ul><ul><li>You must drop a procedure before you create one with the same name </li></ul></ul><ul><ul><li>When you change the source code for the procedure </li></ul></ul>
  15. 15. Input Parameters <ul><li>Stored procedures can accept input parameters. (Most procs are constructed this way.) </li></ul><ul><li>An input parameter is nothing more than a variable that is supplied a value when the user executes the proc </li></ul><ul><li>The input parameter(s) are defined within the stored procedure </li></ul><ul><li>This increases the flexibility of the procedure </li></ul>
  16. 16. Input Parameters <ul><li>create procedure proc_name </li></ul><ul><li>(@parameter datatype </li></ul><ul><li>[,@parameter datatype…]) </li></ul><ul><li>as </li></ul><ul><ul><li>SQL batch </li></ul></ul><ul><li>return </li></ul><ul><li>--Single input parameter </li></ul><ul><li>create procedure myproc </li></ul><ul><li>(@name vahrchar(40)) </li></ul><ul><li>as </li></ul><ul><li>select * from authors where au_lname = @name </li></ul><ul><li>return </li></ul><ul><li>exec myproc ‘Smith’ </li></ul>
  17. 17. Input Parameters <ul><li>Parameter names can be up to 30 characters including the @ </li></ul><ul><li>There can be up to 255 parameters in a procedure </li></ul><ul><li>A value passed to a procedure can contain a wildcard character as long as the parameter is used in a like clause </li></ul><ul><li>An object name can not be passed as a parameter </li></ul>
  18. 18. Executing Procedures <ul><li>A procedure with parameters can be executed two ways: </li></ul><ul><ul><li>by name </li></ul></ul><ul><ul><li>by position </li></ul></ul><ul><li>When a proc is executed by name, the input parameter is explicitly referenced </li></ul><ul><ul><li>exec myproc @name = ‘Smith’ </li></ul></ul><ul><li>When called by position, the arguments are in the order the parameters were defined </li></ul><ul><ul><li>exec myproc ‘Smith’ </li></ul></ul><ul><li>You will very rarely execute a procedure by name. But, executing by name is more self-documenting </li></ul>
  19. 19. Multiple Parameters <ul><li>You can define more than one parameter for a stored procedure </li></ul><ul><li>create proc myproc </li></ul><ul><li>(@var1 int, @var2 int, @var3 char(2)) </li></ul><ul><li>as… </li></ul>
  20. 20. Default Value <ul><li>You do not have to always pass the same number of arguments that have been defined in the procedure </li></ul><ul><li>To allow this, input parameters can be defined with default values </li></ul><ul><li>create procedure proc_name </li></ul><ul><li>(@parameter datatype = default </li></ul><ul><li>[,@parameter datatype = default…]) </li></ul><ul><li>as </li></ul><ul><ul><li>SQL batch </li></ul></ul><ul><li>return </li></ul>
  21. 21. Default Values <ul><li>When executing a procedure, you must pass values for all parameters that do not have defaults assigned to them </li></ul><ul><li>If a parameter is optional, or is usually assigned a particular value, assign a default to that parameter </li></ul>
  22. 22. Common Errors <ul><li>Values are not compatible with the defined datatype </li></ul><ul><li>Parameters are passed via mixed methods; some by name, some by position </li></ul><ul><li>One or more parameters is missing </li></ul><ul><li>Parameters are passed in the wrong order </li></ul>
  23. 23. Stored Procedures <ul><li>Sometimes we need to return values from a stored procedure </li></ul><ul><li>This is accomplished with output parameters </li></ul><ul><ul><li>This is not supported in all DBMSs </li></ul></ul><ul><li>create procedure proc_name </li></ul><ul><li>(@parameter datatype = default </li></ul><ul><li>[,@parameter datatype = default…] </li></ul><ul><li>[,@parameter datatype output…]) </li></ul><ul><li>as </li></ul>
  24. 24. Error Handling <ul><li>You should always implement error handling in your stored procedures </li></ul><ul><li>This includes the use of </li></ul><ul><ul><li>raiserror </li></ul></ul><ul><ul><li>transactions </li></ul></ul><ul><ul><li>return status </li></ul></ul><ul><li>To debug your stored procedures, make use of the print statement to inform you of states of variables and execution branches </li></ul><ul><li>Just make sure to remove these before the procedure goes into production </li></ul>
  25. 25. Output Values <ul><li>create procedure myproc </li></ul><ul><li>(@book_id char(6), </li></ul><ul><li>@total_sales int output) </li></ul><ul><li>as </li></ul><ul><li>select @total_sales = sum(qty) </li></ul><ul><ul><li>from salesdetail </li></ul></ul><ul><ul><li>where title_id = @book_id </li></ul></ul><ul><li>return </li></ul><ul><li>declare @total int </li></ul><ul><li>exec myproc 'PS2091' @total output </li></ul><ul><li>select @total </li></ul><ul><li>-------- </li></ul><ul><li>2045 </li></ul>
  26. 26. Return Status <ul><li>Every procedure will return a status </li></ul><ul><ul><li>0 for successful completion </li></ul></ul><ul><ul><li>-1 to -99 for errors </li></ul></ul><ul><li>Use a return statement to specify a return value </li></ul><ul><ul><li>return 10 </li></ul></ul><ul><li>The return statement does not accept a variable. (This is what the output parameter is for.) </li></ul><ul><li>When returning values from your procedure do not use one of the reserved numbers from SQL Server </li></ul>
  27. 27. Comments <ul><li>Add comments to document functionality </li></ul><ul><li>Establish standards to promote consistency </li></ul><ul><li>Suggestions </li></ul><ul><ul><li>Break large single statements across multiple lines </li></ul></ul><ul><ul><li>Create a common header for all procs </li></ul></ul><ul><ul><ul><li>Purpose </li></ul></ul></ul><ul><ul><ul><li>Return values/data </li></ul></ul></ul><ul><ul><ul><li>How to use </li></ul></ul></ul><ul><ul><ul><li>Description of each parameter and variable </li></ul></ul></ul><ul><ul><ul><li>Modification history </li></ul></ul></ul><ul><ul><ul><li>Author, mod date, and creation date </li></ul></ul></ul><ul><ul><ul><ul><li>I generally don't identify the author, but this is preference </li></ul></ul></ul></ul>
  28. 28. Comments <ul><li>Suggestions con't: </li></ul><ul><ul><li>Include all comments after the as statement </li></ul></ul><ul><ul><ul><li>Any comments included before the as statement will not get included </li></ul></ul></ul><ul><ul><li>Do all variable declarations and assignment selects in a block </li></ul></ul><ul><li>Example </li></ul><ul><li>(Can be found at http://www.mssqlserver.com/articles) </li></ul>
  29. 29. Transaction Control <ul><li>Establish a transaction mode (chained or unchained) for your application -- Sybase only </li></ul><ul><li>Establish a consistent error handling strategy for any failed transaction </li></ul><ul><li>Implement standard procedure templates and transaction control in nested stored procedures to maintain consistency </li></ul>
  30. 30. @@trancount <ul><li>@@trancount contains the nesting level of transaction </li></ul><ul><li>Each begin tran increments the variable </li></ul><ul><li>Each commit decrements the variable </li></ul><ul><li>Rollback resets @@trancount to 0 </li></ul><ul><li>begin tran --@@trancount = 1 </li></ul><ul><li>begin tran --@@trancount = 2 </li></ul><ul><li>begin tran --@@trancount = 3 </li></ul><ul><li>commit --@@trancount = 2 </li></ul><ul><li>rollback --@@trancount = 0 </li></ul>
  31. 31. Nested Procedures <ul><li>You can nest procedures (have one procedure that calls another) up to 16 levels deep </li></ul><ul><li>create proc… </li></ul><ul><li>exec proc2... </li></ul><ul><li>exec proc3... </li></ul><ul><li>return </li></ul>
  32. 32. Nesting <ul><li>A stored procedure containing a transaction can contain another procedure containing a transaction </li></ul><ul><li>Use @@trancount to keep track of the nesting level </li></ul><ul><li>After a commit or rollback in an inner nested procedure, will cause subsequent statements in the outer batch to execute </li></ul><ul><li>Keep in mind the effect of commit and rollback on @@trancount </li></ul>
  33. 33. Nesting and Savepoints <ul><li>Nested transactions that contain savepoints, if rolled back, will not cause the outermost transaction to be rolled back </li></ul><ul><li>In order to achieve this effect, you must explicitly name the savepoint </li></ul><ul><li>save tran xyz... </li></ul><ul><li>rollback tran --Roll back to the savepoint </li></ul><ul><li>save tran xyz… </li></ul><ul><li>rollback --Rolls back everything </li></ul>
  34. 34. Server Cursors <ul><li>Server cursors are cursors that execute within a stored procedure </li></ul><ul><li>They are declared and used exactly as was explained in the cursors unit </li></ul><ul><li>create proc… </li></ul><ul><li>declare mycursor for… </li></ul><ul><li>open mycursor… </li></ul><ul><li>fetch mycursor </li></ul><ul><li>… </li></ul><ul><li>close mycursor </li></ul><ul><li>deallocate mycursor </li></ul><ul><li>return </li></ul>
  35. 35. Cursor Scope <ul><li>A stored procedure can access the cursors that are declared outside the procedure or in other procedures in the call tree </li></ul><ul><li>If a proc pA declares a cursor cA and then calls proc pB, pB can access cursor cA </li></ul><ul><li>If pB declares a cursor cA, then the cursor in pA is no longer available to pB or any procedures that it calls </li></ul>
  36. 36. Standards <ul><li>Add defaults to all input arguments </li></ul><ul><li>Check for missing arguments and print a usage statement </li></ul><ul><li>Check the validity of parameters </li></ul><ul><li>Include return status for error handling </li></ul><ul><li>Print meaningful messages for the user </li></ul><ul><li>Comment your code </li></ul>
  37. 37. Restrictions <ul><li>Some SQL statements can not be used </li></ul><ul><li>Create tables before you refer to them </li></ul><ul><li>A table can not be created, dropped, and recreated in the same procedure </li></ul><ul><li>You must drop a procedure before creating another one of the same name </li></ul><ul><li>Procedures can be nested up to 16 levels deep </li></ul>
  38. 38. Notes <ul><li>Stored procedures can reference objects in another database </li></ul><ul><li>Temporary tables created in a procedure are dropped when the procedure ends </li></ul><ul><li>Set options in a procedure stay in effect for the duration of the procedure and are reset when it ends </li></ul>
  39. 39. Dependencies <ul><li>Stored procedures operate on one or more objects in a database(s) </li></ul><ul><li>Use the sp_depends stored procedure to get a list of objects the stored procedure references </li></ul><ul><li>sp_depends proc_name </li></ul>
  40. 40. Recompile <ul><li>A query plan is created the first time a procedure is executed </li></ul><ul><li>Sometimes, the query plan is out of date or a different query plan should be used </li></ul><ul><li>To cause SQL Server not recreate the query plan, use the with recompile option </li></ul><ul><li>create proc… </li></ul><ul><li>with recompile </li></ul><ul><li>as... </li></ul>
  41. 41. Recompile <ul><li>Use the with recompile only when there is no way to predict the best query plan at compile time </li></ul><ul><li>You can also do this on a one time basis by specifying the with recompile in the execute statement </li></ul><ul><li>exec myproc with recompile </li></ul><ul><li>This is generally done to update a query plan with the statistics now available to the DBMS </li></ul>
  42. 42. Unit 14 Review <ul><li>A stored procedure is a batch of SQL that is compiled and stored in a database </li></ul><ul><li>Some SQL statements can not be used in a procedure </li></ul><ul><li>A stored procedure can use input parameters to increase the flexibility of the procedure </li></ul><ul><li>Input parameters can be created with default values </li></ul><ul><li>Output parameters can be used to return values </li></ul><ul><li>Every procedure will give a return status </li></ul><ul><li>Comments should be placed in procedures to document the code </li></ul><ul><li>A procedure will take on the current transaction mode the session is working under </li></ul><ul><li>Transactions can be nested </li></ul><ul><li>@@trancount keeps track of the current nesting level </li></ul><ul><ul><li>begin increments </li></ul></ul><ul><ul><li>commit decrements </li></ul></ul><ul><ul><li>rollback sets to 0 </li></ul></ul><ul><li>Stored procedures can see cursors declared within their calling tree </li></ul><ul><li>Use the with recompile option to recreate a query plan </li></ul>
  43. 43. Unit 14 Exercises <ul><li>Time allotted for exercises is 1 hour </li></ul>

×