Download - Intro to tsql unit 14
![Page 1: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/1.jpg)
Introduction To SQLUnit 14
Modern Business Technology
Introduction To TSQLUnit 14
Developed by
Michael Hotek
![Page 2: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/2.jpg)
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
![Page 3: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/3.jpg)
• 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
![Page 4: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/4.jpg)
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
![Page 5: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/5.jpg)
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
![Page 6: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/6.jpg)
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
![Page 7: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/7.jpg)
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)
![Page 8: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/8.jpg)
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
![Page 9: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/9.jpg)
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
![Page 10: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/10.jpg)
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
![Page 11: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/11.jpg)
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
![Page 12: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/12.jpg)
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)
![Page 13: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/13.jpg)
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
![Page 14: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/14.jpg)
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
![Page 15: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/15.jpg)
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
![Page 16: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/16.jpg)
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’
![Page 17: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/17.jpg)
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
![Page 18: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/18.jpg)
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
![Page 19: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/19.jpg)
Multiple Parameters
• You can define more than one parameter for a stored procedure
create proc myproc
(@var1 int, @var2 int, @var3 char(2))
as…
![Page 20: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/20.jpg)
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
![Page 21: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/21.jpg)
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
![Page 22: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/22.jpg)
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
![Page 23: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/23.jpg)
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
![Page 24: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/24.jpg)
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
![Page 25: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/25.jpg)
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
![Page 26: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/26.jpg)
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
![Page 27: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/27.jpg)
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
![Page 28: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/28.jpg)
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)
![Page 29: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/29.jpg)
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
![Page 30: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/30.jpg)
@@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
![Page 31: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/31.jpg)
Nested Procedures
• You can nest procedures (have one procedure that calls another) up to 16 levels deep
create proc…
exec proc2...
exec proc3...
return
![Page 32: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/32.jpg)
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
![Page 33: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/33.jpg)
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
![Page 34: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/34.jpg)
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
![Page 35: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/35.jpg)
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
![Page 36: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/36.jpg)
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
![Page 37: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/37.jpg)
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
![Page 38: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/38.jpg)
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
![Page 39: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/39.jpg)
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
![Page 40: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/40.jpg)
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...
![Page 41: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/41.jpg)
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
![Page 42: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/42.jpg)
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
![Page 43: Intro to tsql unit 14](https://reader037.vdocuments.net/reader037/viewer/2022110307/555ec992d8b42af67f8b512d/html5/thumbnails/43.jpg)
Unit 14 Exercises
• Time allotted for exercises is 1 hour