0% found this document useful (0 votes)
3 views

Chapter 4_Using PLSQl Sub Program (1)

This document covers PL/SQL subprograms, including procedures and functions, highlighting their structure, advantages, and examples. It explains the differences between functions and stored procedures in SQL Server, as well as the use of recursive Common Table Expressions (CTEs) for calculations like factorials. The content emphasizes the benefits of modularity, reusability, and maintainability in database programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 4_Using PLSQl Sub Program (1)

This document covers PL/SQL subprograms, including procedures and functions, highlighting their structure, advantages, and examples. It explains the differences between functions and stored procedures in SQL Server, as well as the use of recursive Common Table Expressions (CTEs) for calculations like factorials. The content emphasizes the benefits of modularity, reusability, and maintainability in database programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Advance Database using PL/SQL

Unit 4 : Using PL/SQL Subprograms

PL/SQL Subprograms
• A program separate from the main program that executes a series of operations
that occurs multiple times during the machine cycle.

• A PL/SQL subprogram is a named PL/SQL block that can take parameters and be
invoked repeatedly. If the subprogram has parameters, their values can differ for
each invocation.

• A subprogram is either a procedure or a function. Typically, you use a procedure


to perform an action and a function to compute and return a value.

• Each subprogram will have a name, and also has parameter list same like that of
the anonymous PL/SQL blocks, these have three parts:
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Each subprogram will have a name, and also has parameter list same
like that of the anonymous PL/SQL blocks, these have three parts:
• Declarative part – It is an optional part. However, the declarative part for a
subprogram does not start with the DECLARE keyword. It contains declarations
of types, cursors, constants, variables, exceptions, and nested subprograms.
These items are local to the subprogram and cease to exist when the
subprogram completes execution.
• Executable part – Executable part is said to be the mandatory part and
also has statements that will perform the designated actions.
• Exception-handling – Exception-handling is said to be an optional part
and also contains code that can handle run-time errors.
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Advantages of Subprograms
In Microsoft SQL Server, subprograms are typically implemented using stored procedures, functions, and triggers.
These subprograms offer various advantages that help in managing and manipulating data within the database.
Here are some of the advantages of using subprograms in MS SQL Server:
• Code Reusability: Subprograms allow you to encapsulate a set of SQL statements into a single, reusable unit.
This reduces code duplication and promotes a more modular and maintainable approach to database
development.
• Improved Performance: SQL Server can optimize the execution plan for stored procedures and functions,
resulting in improved query performance.
• Security: You can grant specific permissions to stored procedures and functions, allowing you to control who can
access and modify the data in your database. This helps enhance data security.
• Encapsulation: Subprograms encapsulate business logic and data manipulation within the database. This
separation of concerns makes it easier to maintain and update your application, as changes are isolated to the
subprograms themselves.
• Error Handling: Stored procedures and functions can include error handling logic, making it easier to handle and
report errors in a consistent and controlled manner. This is particularly useful for handling exceptions and
recovering from errors.
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Advantages of Subprograms
• Maintainability: Subprograms make it easier to maintain and update your database schema and
logic. If you need to change a specific operation, you only need to update the subprogram
instead of searching for and modifying multiple instances of the same code.
• Transaction Control: You can explicitly define transaction boundaries within stored procedures.
This allows you to ensure that a series of related SQL statements either all succeed or all fail,
which is crucial for maintaining data consistency.
• Modularity: Subprograms allow you to break down complex operations into smaller,
manageable pieces. This modular approach makes it easier to understand, test, and debug your
code.
• Centralized Logic: By using subprograms, you centralize your data access and manipulation
logic. This ensures that data-related operations are consistent across your application, reducing
the risk of data inconsistencies.
• Parameterization: Stored procedures and functions allow you to use parameters to pass values
to the code, making it more flexible and versatile for various use cases.
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

PL/SQL Procedures
• This is subprograms which do not return a value directly; mainly used to
perform an action.

• A stored procedure is a precompiled collection of one or more SQL statements


or Transact-SQL (T-SQL) statements that are stored in the database and can be
executed as a single unit.
• If you have an SQL query that you write over and over again, save it as a stored
procedure, and then just call it to execute it.
• You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parameter value(s) that is passed.
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

PL/SQL Procedures
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement.
The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as
follows −
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;

CREATE PROCEDURE SelectAllCustomers


@City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Example of PL/SQL Procedures


Use your database MYSTORE, Create procedure to select all Product from table Product
select * from Product
===========================================
==
-- Author:<Suraj>
-- Create date: <10/30/2023>
-- Description:<For selecting all product>
===========================================
==
CREATE PROCEDURE GetAllProduct
AS
BEGIN
select * from Product
END
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Example of PL/SQL Procedures


Execute the stored procedure above as follows:

EXEC GetAllProduct
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Example of PL/SQL Procedures


Alter procedure, to get only ProductName,Salesprice from Product

===========================================
==
-- Author:<Suraj>
-- Create date: <10/30/2023>
-- Description:<For selecting all product>
===========================================
==
ALTER PROCEDURE GetAllProduct
AS
BEGIN
select ProductName,Salesprice from Product
END
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

PL/SQL Function
A function is a database object that allows you to encapsulate a specific piece of
Transact-SQL (T-SQL) logic and return a single value or a table of values as a result.
Functions in SQL Server help improve code organization, maintainability, and
reusability while allowing you to encapsulate specific logic for various data
manipulation tasks.
SQL Server provides two main types of user-defined functions:
• Scalar Function: A scalar function in SQL Server returns a single value, such as an
integer, string, date, or any other data type. It takes input parameters and performs
some calculations or operations on these parameters to produce a single result.
• Table-Valued Function: A table-valued function in SQL Server returns a table of
rows as its result. It can be used to return a set of rows based on some logic or
calculations, making it particularly useful for complex queries or when you need to
reuse a set of rows.
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

PL/SQL System Function


Functions that are defined by the system are known as system functions. In
other words, all the built-in functions supported by the server are referred to as
System functions. The built-in functions save us time while performing the
specific task. These types of functions usually work with the SQL SELECT
statement to calculate values and manipulate data.
Here is the list of some system functions used in the SQL Server:
• String Functions (LEN, SUBSTRING, REPLACE, CONCAT, TRIM)
• Date and Time Functions (datetime, datetime2, smalldatetime)
• Aggregate Functions (COUNT, MAX, MIN, SUM, AVG)
• Mathematical Functions (ABS, POWER, PI, EXP, LOG)
• Ranking Functions (RANK, DENSE_RANK, ROW_NUMBER, NTILE)
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Example of PL/SQL Scaler Function


-- Scalar function that calculates the total price
CREATE FUNCTION dbo.CalculateTotalPrice (@Quantity int, @Price float)
RETURNS float
AS
BEGIN
DECLARE @TotalPrice float
SET @TotalPrice = @Quantity * @Price
RETURN @TotalPrice
END
-- Using a scalar function
SELECT ProductName, dbo.CalculateTotalPrice(5, SalesPrice) AS TotalPrice
FROM Product
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Example of PL/SQL Scaler Function


This function calculates the square of a number.
-- Create a new scalar UDF
CREATE FUNCTION CalculateSquare (@number FLOAT)
RETURNS FLOAT
AS
BEGIN
DECLARE @result FLOAT
SET @result = @number * @number
RETURN @result
END

SELECT dbo.CalculateSquare(5) AS Square


Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Example of PL/SQL Scaler Function


user-defined function (UDF) that calculates the factorial of a given number:
CREATE FUNCTION CalculateFactorial (@number INT)
RETURNS BIGINT
AS
BEGIN
DECLARE @result BIGINT = 1
DECLARE @i INT = 1

WHILE @i <= @number


BEGIN
SET @result = @result * @i
SET @i = @i + 1
END

RETURN @result
END
SELECT dbo.CalculateFactorial(5) AS FactorialOf5
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

Example of PL/SQL Table-valued Function

-- Table-valued function that retrieves products in a category


CREATE FUNCTION dbo.GetProductsInCategory (@CategoryID int)
RETURNS TABLE
AS
RETURN (
SELECT ProductID, ProductName, SalesPrice
FROM Product
WHERE CategoryID = @CategoryID
)

-- Using a table-valued function


SELECT * FROM dbo.GetProductsInCategory(1)
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms
Difference between Functions and Stored Procedures in SQL
Server
Function Stored Procedure
Always returns a single value; either scalar or a table. Can return zero, single or multiple values.
Functions are compiled and executed at run time. Stored procedures are stored in parsed and compiled state in the
database.
Only Select statements. DML statements like update & insert are not Can perform any operation on database objects including select and
allowed. DML statements.
Allows only input parameters. Does not allow output parameters. Allows both input and output parameters

Does not allow the use of Try…Catch blocks for exception handling. Allows use of Try…Catch blocks for exception handling.

Cannot have transactions within a function. Can have transactions within a stored procedure.
Cannot call a stored procedure from a function. Can call a function from a stored procedure.
Temporary tables cannot be used within a function. Only table Both table variables and temporary tables can be used.
variables can be used.
Functions can be called from a Select statement. Stored procedures cannot be called from a Select/Where or Having
statements. Execute statement has to be used to execute a stored
procedure.
Functions can be used in JOIN clauses. Stored procedures cannot be used in JOIN clauses
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

SQL Server Recursive CTE


Sometimes, a stored procedure or function is required to use the results of a sample several times.
In such cases, we often use temporary tables.
A CTE (Common Table Expression) is a one-time result set that only exists for the
duration of the query. It allows us to refer to data within a single SELECT, INSERT, UPDATE,
DELETE, CREATE VIEW, or MERGE statement's execution scope. It is temporary because its result
cannot be stored anywhere and will be lost as soon as a query's execution is completed.

CTE Syntax in SQL Server

1.WITH cte_name (column_names)


2.AS (query)
3.SELECT * FROM cte_name;
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

SQL Server Recursive CTE Example


we use a recursive CTE to calculate the factorial of 5.

WITH RecursiveFactorial AS (
-- Anchor query
SELECT 1 AS N, 1 AS Result
UNION ALL
-- Recursive query
SELECT N + 1, Result * (N + 1)
FROM RecursiveFactorial
WHERE N < 5 -- Termination condition
)
SELECT Result
FROM RecursiveFactorial
WHERE N = 5; -- Final result
Advance Database using PL/SQL
Unit 4 : Using PL/SQL Subprograms

SQL Server Recursive CTE Example


we use a recursive CTE to calculate the factorial of 5.
WITH FactorialCTE AS (
SELECT 1 AS Number, 1 AS Factorial
UNION ALL
SELECT Number + 1, Factorial * (Number + 1)
FROM FactorialCTE
WHERE Number < 10 -- Change the limit to the
desired number
)
SELECT Number, Factorial
FROM FactorialCTE;

You might also like