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

What's hot (20)

PPTX
Advance Sql Server Store procedure Presentation
Amin Uddin
 
PPT
Lecture 2. MS SQL. Stored procedures.
Alexey Furmanov
 
PPTX
Function & procedure
atishupadhyay
 
PPS
Procedures/functions of rdbms
jain.pralabh
 
PPTX
Stored procedure in sql server
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Stored procedure
Deepak Sharma
 
PPTX
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Sql server ___________session_18(stored procedures)
Ehtisham Ali
 
PPTX
Procedures and triggers in SQL
Vikash Sharma
 
PPSX
Sql triggers
Chandan Banerjee
 
PDF
PL/SQL TRIGGERS
Lakshman Basnet
 
PPTX
5. stored procedure and functions
Amrit Kaur
 
PPTX
T-SQL & Triggers
Ayesha Maqsood
 
PPT
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
InSync Conference
 
PDF
Bypass dbms assert
fangjiafu
 
PPT
Asynchronous t sql
Remus Rusanu
 
PPTX
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Performance testing using Jmeter for apps which needs authentication
Jay Jha
 
Advance Sql Server Store procedure Presentation
Amin Uddin
 
Lecture 2. MS SQL. Stored procedures.
Alexey Furmanov
 
Function & procedure
atishupadhyay
 
Procedures/functions of rdbms
jain.pralabh
 
Stored procedure in sql server
baabtra.com - No. 1 supplier of quality freshers
 
Stored procedure
Deepak Sharma
 
Sql server ___________session_18(stored procedures)
Ehtisham Ali
 
Procedures and triggers in SQL
Vikash Sharma
 
Sql triggers
Chandan Banerjee
 
PL/SQL TRIGGERS
Lakshman Basnet
 
5. stored procedure and functions
Amrit Kaur
 
T-SQL & Triggers
Ayesha Maqsood
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
InSync Conference
 
Bypass dbms assert
fangjiafu
 
Asynchronous t sql
Remus Rusanu
 
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Performance testing using Jmeter for apps which needs authentication
Jay Jha
 

Viewers also liked (20)

PDF
RFID in Clinical Trials
Terso Solutions
 
PPT
Hobuse unenaod
eberlein
 
PDF
As4tcp paper
ruralfringe
 
PDF
Singapore property weekly issue 1
Christian Paul Del Rosario
 
DOCX
澎湖
Sabrina Wu
 
PDF
SA Youth Sex Survey 2011 - by Young Africa Live
Praekelt Foundation
 
DOCX
Jobsati
prabhuramyah1010
 
PPT
Relational data as_xml
Harshavardhan Achrekar
 
PPS
Oak Collegiate: June 2011
Norman Ash
 
PPT
What makes great kelloggs pr
impactcommunicationsau
 
PPSX
Subliminal party
juliancho04
 
PPT
Lab4 internet
Haliuka Ganbold
 
PPSX
Homage to sri aurobindo, part 4
Jitendra Sharma
 
PPTX
Presentation smacad
Elin Amberg
 
PPS
Ode à Natureza
110262
 
PPT
презентация2
Тимофей Ефимов
 
PPTX
Trek2Freedom
Susan Thompson
 
PDF
Dan Martell - Learning is the killer feature
momentummi
 
PPT
San Diego 2009
kumarajiva
 
PPTX
composition rules
smithed
 
RFID in Clinical Trials
Terso Solutions
 
Hobuse unenaod
eberlein
 
As4tcp paper
ruralfringe
 
Singapore property weekly issue 1
Christian Paul Del Rosario
 
澎湖
Sabrina Wu
 
SA Youth Sex Survey 2011 - by Young Africa Live
Praekelt Foundation
 
Relational data as_xml
Harshavardhan Achrekar
 
Oak Collegiate: June 2011
Norman Ash
 
What makes great kelloggs pr
impactcommunicationsau
 
Subliminal party
juliancho04
 
Lab4 internet
Haliuka Ganbold
 
Homage to sri aurobindo, part 4
Jitendra Sharma
 
Presentation smacad
Elin Amberg
 
Ode à Natureza
110262
 
презентация2
Тимофей Ефимов
 
Trek2Freedom
Susan Thompson
 
Dan Martell - Learning is the killer feature
momentummi
 
San Diego 2009
kumarajiva
 
composition rules
smithed
 
Ad

Similar to Intro to tsql (20)

PPTX
MS SQL SERVER: Sql Functions And Procedures
sqlserver content
 
PPTX
MS SQLSERVER:Sql Functions And Procedures
sqlserver content
 
PPTX
Stored procedures
MuksNoor
 
PPT
Module04
Sridhar P
 
PDF
A set of SQL(structured query language) statements that are designat.pdf
info430661
 
PPTX
STORED-PROCEDURE.pptxjsjjdjdjcjcjdkksksksk
loreinesel
 
PPTX
Stored procedures in_mysql
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Stored procedures with cursor
baabtra.com - No. 1 supplier of quality freshers
 
PPT
SQl
sarankumarv
 
PPTX
Stored procedures by thanveer danish melayi
Muhammed Thanveer M
 
PPT
stored.ppt
YashaswiniSrinivasan1
 
PPT
Intro to tsql unit 11
Syed Asrarali
 
PDF
Stored procedure Notes By Durgesh Singh
imdurgesh
 
PPT
plsql les01
sasa_eldoby
 
PPTX
Introduction to mysql part 3
baabtra.com - No. 1 supplier of quality freshers
 
PPS
09 qmds2005 session13
Niit Care
 
DOC
Subqueries views stored procedures_triggers_transactions
maxpane
 
PPTX
Unit 3(rdbms)
Jay Patel
 
MS SQL SERVER: Sql Functions And Procedures
sqlserver content
 
MS SQLSERVER:Sql Functions And Procedures
sqlserver content
 
Stored procedures
MuksNoor
 
Module04
Sridhar P
 
A set of SQL(structured query language) statements that are designat.pdf
info430661
 
STORED-PROCEDURE.pptxjsjjdjdjcjcjdkksksksk
loreinesel
 
Stored procedures by thanveer danish melayi
Muhammed Thanveer M
 
Intro to tsql unit 11
Syed Asrarali
 
Stored procedure Notes By Durgesh Singh
imdurgesh
 
plsql les01
sasa_eldoby
 
09 qmds2005 session13
Niit Care
 
Subqueries views stored procedures_triggers_transactions
maxpane
 
Unit 3(rdbms)
Jay Patel
 
Ad

More from Syed Asrarali (11)

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

Recently uploaded (20)

PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 

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