0% found this document useful (0 votes)
20 views37 pages

Lecture2 DBP2024

Visual programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views37 pages

Lecture2 DBP2024

Visual programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

LECTURE2

Stored Procedure in SQL Server-


Stored Procedure in SQL Server
 What happens when we execute a simple SQL statement in SQL
Server?
When any SQL Statements are fired on SQL Server, then three steps are
happening in order which is shown in the below image.
Stored Procedure in SQL Server
 The first time the SQL is executed, the syntaxes are checked, the execution plan is selected and
the execution plan is cached in memory.
 So, if the same SQL statements are fired again, then these two steps are not going to be executed,
rather the execution plan is taken from the cache and executed and that will definitely increase the
performance of the application which is shown in the below image.

 This is what exactly the stored procedure does in SQL Server.


Stored Procedure in SQL Server
• What is a Stored Procedure in SQL Server?
A SQL Server Stored Procedure is a database object which contains pre-
compiled queries (a group of T-SQL Statements).
• How can we create a Stored Procedure in SQL Server?
In SQL Server, you can create a stored procedure by using the
CREATE PROCEDURE or CREATE PROC , and you can create a procedure
with or without parameters.
Stored Procedure in SQL Server
Stored Procedure in SQL Server
 A stored procedure is very much similar to a function in C, C++
languages or a method in Java or C# languages. The procedure
definitions contain two parts in it
1. Procedure header
2. Procedure body
Stored Procedure in SQL Server
• How to call a Stored Procedure in SQL Server?
There are three different way for calling stored procedure
Stored Procedure in SQL Server
Stored Procedure in SQL Server Without Parameter
 Examples:
1. Create stored procedure to print a welcome message on the
screen?
CREATE PROCEDURE spDisplayWelcome
AS
BEGIN
PRINT 'WELCOME TO PROCEDURE in SQL
Server'
END
Stored Procedure in SQL Server
2. Create a stored procedure to get the names, gender, and the dob of
all employees from the table Employee table.

CREATE PROCEDURE spGetEmployee


AS
BEGIN
Select Name, Gender, DOB from Employee
END
Stored Procedure in SQL Server
How to View the text of a Stored Procedure in SQL Server?
By using the sp_helptext --system-defined stored procedure
• Example: sp_helptext spDisplayWelcome
Stored Procedure in SQL Server
• How to change the name and body of a stored procedure in SQL
Server? CREATE PROCEDURE spGetEmployee
As
BEGIN
SELECT Name,Gender, DOB FROM Employee
Change END
-- How to change the body of a stored procedure
the body -- User Alter procedure to change the body
ALTER PROCEDURE spGetEmployee
AS
BEGIN
SELECT Name, Gender, DOB
FROM Employee
ORDER BY Name
END

-- To change the procedure name from spGetEmployee to


Change spGetEmployee1
the name -- Use sp_rename system defined stored procedure
EXEC sp_rename 'spGetEmployee', 'spGetEmployee1'
Stored Procedure in SQL Server
• How to Drop a Stored Procedure?
syntax for to drop a stored procedure
DROP PROCEDURE ProcedureName
Example:
Drop proc spGetEmployee1
or Drop Procedure spGetEmployee1
Stored Procedure in SQL Server
Different Types of Parameters in SQL Server Stored Procedure.
The parameters of a Stored Procedure in SQL Server can be of two
types
1. Input parameters
2. Output parameters
Stored Procedure in SQL Server
Understanding the Input Parameters in SQL Server Procedure:
• Example. create a procedure that will take two input integer
parameters and then perform the sum operation and finally print the
result. -- Create a Procedure
ALTER PROCEDURE spAddTwoNumbers(@no1 INT, @no2
INT)
AS
BEGIN
DECLARE @Result INT
SET @Result = @no1 + @no2
PRINT 'RESULT IS: '+ CAST(@Result AS VARCHAR)
END
GO
Stored Procedure in SQL Server

-- Calling the procedure:


EXECUTE spAddTwoNumbers 10, 20

-- OR
EXECUTE spAddTwoNumbers @no1=10, @no2=20

-- OR calling the procedure by declaring two variables as shown


below
DECLARE @no1 INT, @no2 INt
SET @no1 = 10
SET @no2 = 20
EXECUTE spAddTwoNumbers @no1, @no2
Stored Procedure in SQL Server
Example: Create a procedure to update the Employee details in the
Employee table based on the Employee id.
CREATE PROCEDURE spUpdateEmployeeByID
( @ID INT,
@Name VARCHAR(50),
@Gender VARCHAR(50), @DOB DATETIME,
@DeptID INT)
AS
BEGIN
UPDATE Employee SET
Name = @Name,
Gender = @Gender,
DOB = @DOB,
DeptID = @DeptID
WHERE ID = @ID
END
Stored Procedure in SQL Server

-- Executing the Procedure


-- If you are not specifying the Parameter Names then the order is
important
EXECUTE spUpdateEmployeeByID 3, 'Palak', 'Female', '1994-06-17
10:53:27.060', 3
-- If you are specifying the Parameter Names then order is not mandatory
EXECUTE spUpdateEmployeeByID @ID =3, @Gender = 'Female', @DOB = '1994-
06-17 10:53:27.060', @DeptID = 3, @Name = 'Palak'
Stored Procedure in SQL Server
SQL Server Stored Procedure Output Parameters:
• Example: Create a simple stored procedure to summation two
number and return result.
CREATE PROCEDURE spGetResult
@No1 INT,
@No2 INT,
@Result INT OUTPUT
AS
BEGIN
SET @Result = @No1 + @No2
END

-- To Execute Procedure
DECLARE @Result INT
EXECUTE spGetResult 10, 20, @Result OUT
PRINT @Result
Stored Procedure in SQL Server
 Example2:Create a stored procedure to get the total number of
employees in the Employee table by Gender.
CREATE PROCEDURE spGetEmployeeCountByGender
@Gender VARCHAR(30), @EmployeeCount INT
OUTPUT
AS
BEGIN
SELECT @EmployeeCount = COUNT(ID)
FROM Employee
WHERE Gender = @Gender
END
-- To Execute Procedure
DECLARE @EmployeeTotal INT
EXECUTE spGetEmployeeCountByGender 'Male', @EmployeeTotal
OUTPUT
PRINT @EmployeeTotal
Stored Procedure in SQL Server
Stored Procedure with Default Values:
Let’s see an example of how to use the stored procedure with default values.
CREATE PROCEDURE spAddNumber(@No1 INT= 100,
@No2 INT)
AS
BEGIN
DECLARE @Result INT
SET @Result = @No1 + @No2
PRINT 'The SUM of the 2 Numbers is: '+
CAST(@Result AS VARCHAR)
END
-- Executing the above procedure:
EXEC spAddNumber 3200, 25
EXEC spAddNumber @No1=200, @No2=25
EXEC spAddNumber @No1=DEFAULT, @No2=25
EXEC spAddNumber @No2=25
Stored Procedure in SQL Server
What are the advantages of using a Stored Procedure in an SQL
Server?
• Execution Plan Retention which Improves the Application
Performance.
• Reduces the Network Traffic.
• Code Re-usability and Better Maintainability.
• Better Security .
Stored Procedure in SQL Server
SQL Server Stored Procedure Return Value
• What is Return Value in SQL Server Stored Procedure?
Whenever we execute a stored procedure in SQL Server, it always
returns an integer status variable indicating the status, usually, zero
indicates success, and non-zero indicates the failure.
Stored Procedure in SQL Server
• Example1:Create a procedure that will count the total number of
employees in the Employee table using return status.
CREATE PROCEDURE spGetTotalCountOfEmployee2
AS
BEGIN
RETURN (SELECT COUNT(ID) FROM Employee)
END

-- For calling the procedure:


DECLARE @EmployeeTotal INT
EXECUTE @EmployeeTotal =
spGetTotalCountOfEmployee2
PRINT @EmployeeTotal
Stored Procedure in SQL Server
• Example: Create a procedure that will take the id value of an
employee and return the name of that employee using return status
REATE PROCEDURE spGetEmplloyeeNameById2
@ID INT
AS
BEGIN
RETURN (SELECT Name FROM Employee WHERE ID = @ID)
END
GO
-- For calling the procedure:
DECLARE @EmployeeName VARCHAR(30)
EXECUTE @EmployeeName = spGetEmplloyeeNameById2 3
PRINT @EmployeeName

When we execute the spGetEmplloyeeNameById2 Stored Procedure it returns an error stating ‘Conversion failed
when converting the nvarchar value Anurag to data type int.
Stored Procedure in SQL Server
 What are the differences between Return Status Value and Output
Parameters in SQL Server Stored Procedure?
Return Status Variable Output parameters
Only integer data type it can Any data type value it can
return return
Only one value More than one value
Use to indicate success or Use to return values like name,
failure age, salary, count, etc.
Stored Procedure in SQL Server
SQL Server Temporary Stored Procedure
• The stored procedures which are created temporarily in a database i.e. the
stored procedures which are not stored permanently in a database are called
temporary stored procedures.
The SQL Server Temporary Stored Procedures are of two types such as
1. Private/Local Temporary Stored Procedure
2. Public/Global Temporary Stored Procedure.
Stored Procedure in SQL Server
What is a Private/Local Temporary Stored Procedure?
 When we created the stored procedure by using the # prefix before
the stored procedure name then it is called Local or Private
Temporary Stored Procedure
 The Private/Local stored procedures are executed by the connection
which has created it.
 These are automatically deleted when the connection created is
closed
Stored Procedure in SQL Server
 Example: Creating a Local Temporary Stored Procedure in SQL
Server.
CREATE PROCEDURE #LocalProcedure
AS
BEGIN
PRINT 'This is Local Temporary Procedure'
END

-- Calling the Local Temporary Procedure


EXEC #LocalProcedure
Stored Procedure in SQL Server
What are Public/Global Temporary Stored Procedures?
• Whenever the stored procedure is created by using the ## prefix then
it is called Global Temporary Procedure in SQL Server.
• The Global temporary stored procedures are accessed by other
connections in SQL Server.
• The Global Temporary Stored Procedure can access by any connection
until the connection which has created the procedure is not closed.
Stored Procedure in SQL Server
 Example: Creating a Global SQL Server Temporary Stored Procedure.

CREATE PROCEDURE ##GlobalProcedue


AS
BEGIN
PRINT 'This is Global Temporary
Procedure'
END

-- Calling the Global Temporary Procedure


EXEC ##GlobalProcedue
Stored Procedure in SQL Server
• Learning Some useful system-defined stored Procedure in SQL
Server.
system-defined stored functionality
sp_help SP_Name: View the information about the stored procedure, like
parameter names, their datatypes, etc. sp_help can be used with any
database object, like tables, views, SP's, triggers, etc

sp_helptext SP_Name: View the Text of the stored procedure


sp_depends SP_Name: View the dependencies of the stored procedure. This system
SP is very useful, especially if you want to check if there are any stored
procedures that are referencing a table that you are about to drop.
. sp_depends can also be used with other database objects like table etc.

we created a stored procedure or function then the content or text of the function or procedure is going to be saved under
the syscomments system table
Stored Procedure in SQL Server
SQL Server Stored Procedure Encryption and Recompile Attribute:
There are two types of attributes that can be used while creating a
stored procedure in SQL Server, they are as follows
1. With Encryption Attribute
2. With Recompile Attribute
Stored Procedure in SQL Server
 The With Encryption Attribute in SQL Server Stored Procedure:
Create the stored procedure using the “With Encryption” option then
you cannot view the text or content of the stored procedure by using
the sp_helptext
Stored Procedure in SQL Server
 Example :
--Stored Procedure without using the With Encryption
attribute
SELECT * FROM SYSCOMMENTS WHERE ID =
OBJECT_ID('spDisplayWelcome')
sp_helptext spDisplayWelcome
Stored Procedure in SQL Server
--Stored Procedure using the With Encryption attribute
Alter PROCEDURE spDisplayWelcome
With Encryption
AS
BEGIN
PRINT 'WELCOME TO PROCEDURE in SQL Server'
END
SELECT * FROM SYSCOMMENTS WHERE ID =
OBJECT_ID('spDisplayWelcome')
sp_helptext spDisplayWelcome
Stored Procedure in SQL Server
With Recompiled Attribute in SQL Server Stored Procedure:
• Whenever a procedure is compiled for the first time it prepares the best execution plan
according to the current state of the database. Then it executes that query plan when the
procedure is called.
• If the procedure is created by using the Recompile Attribute. Then it is forced to be compiled
each time it is executed and whenever it compiles it prepares the execution plan.
• Forcing a procedure for recompilation and prepared the execution plan is required when the
database undergoes significant changes to its data or structure.
• Another reason to force a procedure to recompile is if at all the tables are added with new
indexes from which the procedure might be benefited forcing for recompilation is very
important because we cannot wait until the server is restarted for preparing a new query plan.
Stored Procedure in SQL Server
 Example
--With Recompiled Attribute in SQL Server Stored
Procedure:

ALTER Procedure sp_GetEmployeeDetailsById


(
@ID INT
)
WITH RECOMPILE
AS
BEGIN
SELECT Name, Gender, CAST(DOB AS DATE) AS DOB
FROM Employee
WHERE ID = @ID
END

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy