STORE PROCEDURE PRESENTATION Presented By – Prabhu P
Nov 21, 2014
STORE PROCEDURESTORE PROCEDURE
PRESENTATION
Presented By – Prabhu P
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= EmpId
End
-- =============================================-- 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)
Beginreturn 1
Endelse
Begindelete 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.
• SyntaxEXEC SP_NAME
ImplementationEXEC 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!
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: Resolution
The 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 Plan
Stored 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.
Advantage Advantage 1: Stored procedures are modular Advantage 2: Stored procedures are tunable Stored procedures are usually written by database
developers/administrators.
Thanks