advance sql server store procedure presentation
TRANSCRIPT
STORE PROCEDURESTORE PROCEDURE
PRESENTATION
Presented By – Amin Uddin
Overview• About Store Procedure • Difference between SP and Function• How to create a store procedure• How to call.• Initial Processing - Review
ResolutionCompilation/OptimizationExecution/Recompilation
• Recompilation Issues When do you want to Recompile?Options for Recompilation? What to Recompile?
What is store procedure?• A stored procedure is a set of SQL commands that has been compiled and stored on the database server.
Once the stored procedure has been "stored", client applications can execute the stored procedure over and over again without sending it to the database server again and without compiling it again.
Stored procedures improve performance by reducing network traffic and CPU load.
Comparison with dynamic SQL
• Remove overhead•Avoidance of network traffic•Encapsulation of business logic•Delegation of access-rights•Some protection from SQL injection attacks
Comparison with functions• 1.Procedure can return zero or n values whereas function can return one
value which is mandatory.
2.Procedures can have input,output parameters for it whereas functions can have only input parameters.
3.Procedure allow select as well as DML statement in it whereas function allow only select statement in it.
4.Functions can be called from procedure whereas procedures cannot be called from function.
5.Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
6.We can go for transaction management in procedure whereas we can't go in function.
7.Functions can run an executable file from SQL SELECT or an action query.operating system use Execute or Exec to run
How To Create And Execute SP
There are various options that can be used to create stored procedures. In these next few topics we will discuss creating a stored procedure and How to execute.
Syntax Of Store ProcedureWith Parameter
-- =============================================-- Author: <Author,,Name>-- Create date: <Create Date,,>-- Description:<Description,,>-- =============================================Create Proc SP_Name(
Param1 DataType,param2 DataType,Param3 DataType,...Paramn DataType
)As
BeginBody Of Store Procedure
End
Implementation:-- =============================================
-- Author: <Author: XYZ>-- Create date: <Create Date:23/06/2010>-- Description: < Used to retrieve all information of an
employee Information of from the Table ‘EmployeeInfo’ according to supplied Employee ID>-- =============================================Create Proc SP_FetchSpecificEmployeeInfo(
EmpId verchar(50))As
BeginSelect * from EmployeeInfo where EmployeeID=
EmpIdEnd
-- =============================================-- Author: <Author,,Name>-- Create date: <Create Date,,>-- Description:<Description,,>-- =============================================
Create Proc SP_NameAsBegin
Body Of Store ProcedureEnd
Syntax Of Store Procedure
With out Parameter
Implemetaion-- =============================================
-- Author: <Author: XYZ>-- Create date: <Create Date:23/06/2010>-- Description: < Used to retrieve all information of the
table ‘EmployeeInfo’ without any Condition>-- =============================================Create Proc SP_FetchAllEmployeeInfo As
BeginSelect * from EmployeeInfo
End
Using SP How To Insert Information
-- =============================================-- Author: < XYZ>-- Create date: <23/06/2010>-- Description: < Used To Insert Employee Information >
-- =============================================CREATE proc SP_InsertEmployeeInfo(
@ID varchar(20) ,@Name varchar (50) ,@Pin varchar(20),@Email varchar(50),@MobileNo varchar(20),@PhoneNo varchar(20),@MailingAddr varchar(500) ,@ParmanentAddr Varchar(500) ,@Sex varchar(10) ,@JoingDate smalldatetime ,@Post varchar(50)
)
ASBegin
if exists(Select ID From EmployeeInfo Where ID = @ID)Begin
return 0Endelse
BeginInsert into EmployeeInfo(
ID,Name,Pin,Email,MobileNo,PhoneNo,MailingAddr ,ParmanentAddr ,Sex,JoingDate,Post
)
values(
@ID,@Name,@Pin,@Email,@MobileNo,@PhoneNo,@MailingAddr ,@ParmanentAddr ,@Sex,@JoingDate,@Post
)End
Beginreturn 1
End
End
Using SP How To Update Information-- =============================================
-- Author: < XYZ>-- Create date: <3/06/2010>-- Description: <Used To Update Record Of EmployeeInfo Table >
-- =============================================CREATE proc SP_UpdateEmployeeInfo(
@ID varchar(20) ,@Name varchar (50) ,@Pin varchar(20),@Email varchar(50),@MobileNo varchar(20),@PhoneNo varchar(20),@MailingAddr varchar(500) ,@ParmanentAddr Varchar(500) ,@Sex varchar(10) ,@JoingDate smalldatetime ,@Post varchar(50)
)
ASBegin
if not exists(select id from EmployeeInfo where ID = @ID)Begin
return 0End
elseBegin
Update EmployeeInfosetName =@Name,Pin =@Pin,Email =@Email,MobileNo =@MobileNo,PhoneNo =@PhoneNo,MailingAddr = @MailingAddr,ParmanentAddr =@ParmanentAddr,Sex =@Sex,JoingDate =@JoingDate,Post =@Post
where ID =@IDreturn 1
End
End
Using SP How TO Delete Record -- =============================================
-- Author: < XYZ>-- Create date: <3/06/2010>-- Description: <Used To Delete Record From EmployeeInfo Table
>-- =============================================CREATE PROC SP_DeleteEmployeeInfo(
@id varchar(20))AS
Begin if not exists(select id from EmployeeInfo where id = @id)
Begin return 0
End else
Beginif exists(select * from EmployeeInfo where id = @id and
DeleteStatus = 0)Begin
return 1End
elseBegin
delete from EmployeeInfo where id = @idreturn 2
EndEnd
End
How To Execute SP• If in a SP , there is no parameter then it executes the following
way.• Syntax
EXEC SP_NAME Implementation
EXEC SP_FetchAllEmployeeInfo
• If in a SP, there is one or more parameters then it executes the following way.
• Syntax • EXEC SP_NAME PARAMETER_lIST Implementation EXEC SP_FetchAllEmployeeInfo ‘001’
How To Perform Execute SP
Processing of Stored Procedures
Compiled plan placed inunified cache
Compiled plan placed inunified cacheCompilationCompilation
Execution(first time
or recompile)
Execution(first time
or recompile)
Resolution*Resolution*
OptimizationOptimization
ParsingParsing
ResolutionResolutionCreationCreation
sysobjectsName, type, etc.
syscomments Text of objectsyscolumns
Parameter listsysdepEnds
Object depEndencies
sysobjectsName, type, etc.
syscomments Text of objectsyscolumns
Parameter listsysdepEnds
Object depEndencies
Initial Steps• When a stored procedure is created all objects
referenced are resolved (checked to see whether or not they exist).
• The create will succeed even if the objects do not exist Procedures called that do not exist generate error
Cannot add rows to sysdepEnds for the current stored procedure because it depEnds on the missing object 'missingobjectname'. The stored procedure will still be created.Benefit: Recursion is allowed!
Tables, Views, Functions called that do not exist - do NOT generate error (unless in 6.5 compatibility mode)
• Verify depEndencies with sp_depEnds before dropping an object
Storing and Executing Procedures
When you create a stored procedure, the server stores the text of the procedure in the syscomments table of the current database. In addition, form of the procedure, called a query tree , in the sysprocedures table. The server uses the query tree to create a query plan and then execute.
Building the Query Tree: ResolutionThe process of building a query tree is called resolution. This process parses the SQL into a more efficient format and resolves all objects representations.
For example, table names are resolved into their object IDs and column names are resolved into their column IDs.
Building the Query Plan: Compilation
The process of building a query plan is called compilation. Adaptive Server builds a query plan on the first execution of a stored procedure. Adaptive Server reads the corresponding query tree from the sysprocedures table and loads it into the procedure cache. The server then creates procedure cache. The query plan is the optimized data access path that Adaptive Server uses to execute the procedure.
Adaptive Server determines the optimal data access path and builds the query plan based on the following information:
• The SQL stored in the query tree• Statistics for each table and index referenced • in the procedure
•The values of any parameters passed to the procedure on the first execution.
Multiple Users and the Query PlanStored procedures are reusable, not reentrant. This means that
only one user at a time can execute a given copy of a procedure's query plan. the same procedure at the same time, Adaptive Server creates an additional query plan based on the parameters used in the later execution.
procedure, the query plan is available in cache for reuse by anyone with execute permissions.
If the server must generate a second query plan for a stored procedure, there is no guarantee that it is the same as the first.
When to recompile? When the plan for a given statement within a
procedure is not consistent in execution plan – due to parameter and/or data changes
Cost of recompilation might be significantly less than the execution cost of a bad plan!Why?
Faster Execution with a better plan Saving plans for reuse is NOT always
beneficial Some plans should NEVER be saved
Recompilation IssuesRECOMPILATION = OPTIMIZATION
OPTIMIZATION = RECOMPILATION
When do you want to recompile? What options do you have Recompilation? How do you know you need to recompile? Do you want to recompile the entire
procedure or only part of it? Can you test it?
Procedure RecompilationThe process of building a query plan is called compilation. Recompilation is the creation of a new query plan from the existing query tree. one of the following events occurs:
•The procedure is loaded from disk to the procedure cache.
• You drop an index on any table referred to in the procedure.
• All copies of the execution plan in cache are currently in use and another user wants to execute the procedure.
• You execute a procedure using the with recompile option.
Procedure Re-resolutionLike recompilation, re-resolution causes the generation of a new plan. In addition, re-resolution updates the existing query tree in theRe-resolution occurs when one of the tables changes in such a way that the query tree stored in the sysprocedures table may be invalid. IDs, or other parts of the table may have changed. In this case, Adaptive Server must rebuild some parts of the query tree.
Adaptive Server re-resolves procedures after you do any of the following:
• Execute the procedure for the first time after a load database.
• Drop and re-create any table used or referenced by the procedure.
• Drop and re-create a database containing a referenced table.
• Bind or unbind a default or rule to a table referred to by a query in the procedure.
Options for Recompilation CREATE … WITH RECOMPILE
When procedure returns widely varying resultsWhen the plan is not consistent
EXECUTE … WITH RECOMPILEFor testing and to determine if CREATE WITH
RECOMPILE is necessary sp_recompile objname
Forces all plans with regard to that object to be invalidated (note: this does not force recompilation on views even though a view name is supported)
Statement Recompilation Dynamic String Execution or Modularized Code
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
Thanks