Your SlideShare is downloading. ×
Intro to tsql
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Intro to tsql


Published on

Published in: Education

1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 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
    • 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
    • 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
  • 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