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

More Related Content

PPT
Intro to tsql unit 15
PPT
Intro to tsql unit 12
PPT
Intro to tsql unit 6
PPTX
Store procedures
PPTX
Sql Functions And Procedures
PPTX
Sql storeprocedure
PDF
Stored-Procedures-Presentation
Intro to tsql unit 15
Intro to tsql unit 12
Intro to tsql unit 6
Store procedures
Sql Functions And Procedures
Sql storeprocedure
Stored-Procedures-Presentation

What's hot (20)

PPTX
Advance Sql Server Store procedure Presentation
PPT
Lecture 2. MS SQL. Stored procedures.
PPTX
Function & procedure
PPS
Procedures/functions of rdbms
PPTX
Stored procedure in sql server
PPTX
Stored procedure
PPTX
PPTX
Sql server ___________session_18(stored procedures)
PPTX
Procedures and triggers in SQL
PPSX
Sql triggers
PDF
PL/SQL TRIGGERS
PPTX
5. stored procedure and functions
PPTX
T-SQL & Triggers
PPT
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
PDF
Bypass dbms assert
PPT
Asynchronous t sql
PPTX
Chapter 4 functions, views, indexing
PPTX
Performance testing using Jmeter for apps which needs authentication
Advance Sql Server Store procedure Presentation
Lecture 2. MS SQL. Stored procedures.
Function & procedure
Procedures/functions of rdbms
Stored procedure in sql server
Stored procedure
Sql server ___________session_18(stored procedures)
Procedures and triggers in SQL
Sql triggers
PL/SQL TRIGGERS
5. stored procedure and functions
T-SQL & Triggers
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Bypass dbms assert
Asynchronous t sql
Chapter 4 functions, views, indexing
Performance testing using Jmeter for apps which needs authentication
Ad

Viewers also liked (20)

PDF
RFID in Clinical Trials
PPT
Hobuse unenaod
PDF
As4tcp paper
PDF
Singapore property weekly issue 1
DOCX
澎湖
PDF
SA Youth Sex Survey 2011 - by Young Africa Live
DOCX
PPT
Relational data as_xml
PPS
Oak Collegiate: June 2011
PPT
What makes great kelloggs pr
PPSX
Subliminal party
PPT
Lab4 internet
PPSX
Homage to sri aurobindo, part 4
PPTX
Presentation smacad
PPS
Ode à Natureza
PPT
презентация2
PPTX
Trek2Freedom
PDF
Dan Martell - Learning is the killer feature
PPT
San Diego 2009
PPTX
composition rules
RFID in Clinical Trials
Hobuse unenaod
As4tcp paper
Singapore property weekly issue 1
澎湖
SA Youth Sex Survey 2011 - by Young Africa Live
Relational data as_xml
Oak Collegiate: June 2011
What makes great kelloggs pr
Subliminal party
Lab4 internet
Homage to sri aurobindo, part 4
Presentation smacad
Ode à Natureza
презентация2
Trek2Freedom
Dan Martell - Learning is the killer feature
San Diego 2009
composition rules
Ad

Similar to Intro to tsql (20)

PPTX
MS SQL SERVER: Sql Functions And Procedures
PPTX
MS SQLSERVER:Sql Functions And Procedures
PPTX
Stored procedures
PPT
Module04
PDF
A set of SQL(structured query language) statements that are designat.pdf
PPTX
STORED-PROCEDURE.pptxjsjjdjdjcjcjdkksksksk
PPTX
PPTX
PPT
PPTX
Stored procedures by thanveer danish melayi
PPT
PPT
Intro to tsql unit 11
PDF
Stored procedure Notes By Durgesh Singh
PPT
plsql les01
PPTX
PPS
09 qmds2005 session13
DOC
Subqueries views stored procedures_triggers_transactions
PPTX
Unit 3(rdbms)
MS SQL SERVER: Sql Functions And Procedures
MS SQLSERVER:Sql Functions And Procedures
Stored procedures
Module04
A set of SQL(structured query language) statements that are designat.pdf
STORED-PROCEDURE.pptxjsjjdjdjcjcjdkksksksk
Stored procedures by thanveer danish melayi
Intro to tsql unit 11
Stored procedure Notes By Durgesh Singh
plsql les01
09 qmds2005 session13
Subqueries views stored procedures_triggers_transactions
Unit 3(rdbms)

More from Syed Asrarali (11)

PPT
Intro to tsql unit 14
PPT
Intro to tsql unit 13
PPT
Intro to tsql unit 10
PPT
Intro to tsql unit 9
PPT
Intro to tsql unit 8
PPT
Intro to tsql unit 7
PPT
Intro to tsql unit 5
PPT
Intro to tsql unit 4
PPT
Intro to tsql unit 3
PPT
Intro to tsql unit 2
PPT
Intro to tsql unit 1
Intro to tsql unit 14
Intro to tsql unit 13
Intro to tsql unit 10
Intro to tsql unit 9
Intro to tsql unit 8
Intro to tsql unit 7
Intro to tsql unit 5
Intro to tsql unit 4
Intro to tsql unit 3
Intro to tsql unit 2
Intro to tsql unit 1

Recently uploaded (20)

PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Insiders guide to clinical Medicine.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
master seminar digital applications in india
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
01-Introduction-to-Information-Management.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Basic Mud Logging Guide for educational purpose
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Institutional Correction lecture only . . .
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
TR - Agricultural Crops Production NC III.pdf
O7-L3 Supply Chain Operations - ICLT Program
Insiders guide to clinical Medicine.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
master seminar digital applications in india
O5-L3 Freight Transport Ops (International) V1.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Anesthesia in Laparoscopic Surgery in India
01-Introduction-to-Information-Management.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Complications of Minimal Access Surgery at WLH
PPH.pptx obstetrics and gynecology in nursing
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Final Presentation General Medicine 03-08-2024.pptx
Basic Mud Logging Guide for educational purpose
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Institutional Correction lecture only . . .
Abdominal Access Techniques with Prof. Dr. R K Mishra
TR - Agricultural Crops Production NC III.pdf

Intro to tsql

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