Section 5
Section 5
DATABASE
SYSTEM 2
Lesson 3. Stored Procedure
• Stored Procedure in SQL Server can be defined as the set of logical group of SQL statements which
are grouped to perform a specific task.
• The main benefit of using a stored procedure is that it increases the performance of the database.
• The benefit of this is that network traffic is greatly reduced, because multiple T-SQL statements are
not forced to travel over the network individually.
• Only the name of the stored procedure to execute and the parameters to it need to be transmitted.
Benefits
• Simplify repeated tasks
• Run Faster
Stored procedures are cached on the server
• Reduce network traffic
• Help to provide security
Limit direct access to tables via defined roles in the database
• Errors can be handled in procedure code without being passed directly to client applications.
• Protecting against some SQL injection attacks.
• Stored procedures can be written once and accessed by many applications.
pg. 1
1- Create Procedure
Syntax:
Example:
create procedure insertProc @id int, @name nvarchar(100), @salary money as
Begin
end
2 EXECUTE Procedure
A stored procedure is used in the SQL Server with the help of the "Execute" or "Exec" Keyword.
Example:
Example:
pg. 2
3- DROP Procedure
Syntax:
4 ALTER Procedure
pg. 2
Example:
Example :
pg. 3
7 Output Parameter
begin
end
pg. 4
8 Return Values
create procedure
spGetEmpCountByGender2 @gender
char(10)
as
begin
return (select count(*) from Employee where
gender =@gender)
end pg. 4
Executing the procedure
declare @x int
execute @x= spGetEmpCountByGender2 'male' print @x
name,count()
pg. 5
Exercise 3
Design the following table and then answer the following questions: