Advanced Database Lab part About Function
Advanced Database Lab part About Function
SQL Functions
SQL functions are simply sub-programs, which are commonly used and re-
used throughout SQL database applications for processing or manipulating
data. All SQL database systems have DDL (data definition language) and
DML (data manipulation language) tools to support the creation and
maintenance of databases.
.
SQL Functions
DDL is responsible for tasks related to database creation, modification, and
maintenance, while DML is responsible for tasks related to the manipulation
of data, which essentially means DML is the programming interface of the
database. The DML, like other programming languages, consists of
instructions which are used to process or compute data within the database.
The DML also supports functions, and these are referred to as SQL
functions. SQL functions are small programs that may have zero or more
input parameters but can return only one value
Why we need Function In SQL
There are many advantages of using functions.
A function needs to be written only once and can be reused multiple
times. This saves time and effort and supports modular programming.
Functions improve performance and efficiency of the database. SQL
functions are compiled and cached before use.
Complex programming logic can be decomposed into a number of
smaller and simpler functions, thus making it easier to understand and
maintain.
Classification of SQL Function
There are many ways to classify SQL functions.
built-in functions and : The built-in functions are standard functions
which are already provided by the SQL database system
user-defined functions: user-defined functions are functions which are
created by the user for a specific purpose.
Built-in functions
SQL provides many built-in functions to perform operations on data. These
functions are useful while performing mathematical calculations, string
concatenations, sub-strings etc
SQL built-in functions are divided into two categories,
Aggregate Functions
Scalar Functions
Aggregate Functions
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a
column.
Useful aggregate functions:
AVG() - Returns the average value
COUNT() - Returns the number of rows
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
The scalar functions
The scalar functions act on the input values and can return
text, numeric, or time and date values.
Examples:
Trim()
Concat()
Current_Time()
Current_Date()
Len()
Some SQL Function Examples
Examples
We'll be using the table named 'EmpSalary' shown here for all the examples discussed.
Example : use of len()
SELECT employeeNo, FirstName, len(FirstName) as FirstNameLength FROM EmpSalary;
Example 2 Concat and trim
SELECT employeeNo, concat(trim(LastName),', ',trim(FirstName)) as fullName,
len(concat(trim(LastName),', ',trim(FirstName))) as lengthOfFullName from EmpSalary;
In this SQL statement, there are three built-in functions used: concat, trim, and len. The
output after execution is as shown in the diagram here.
Cont.
The key point to note here is that every function acts on each row of data, and
a function can contain another function.
The trim function removes trailing blanks from any field.
The concat function then concatenates the firstName and lastName fields,
inserting a comma in between to produce the complete name.
The len function gives the length of the full name, including the comma
and blank space in between firstName and lastName.
Cont.
Now, let's take an example of aggregate functions. As the name
suggests, aggregate functions acts on an aggregate or group of records
in the table.
SELECT department, count(department) as noEmployees, sum(salary)
as totalDeptSal, avg(salary) as avgDeptSal from empSalary group by
department;
SELECT dbo.NoParameters()
Create SQL Function with parameters
example
Example1: Create a Function in SQL Server which will return the cube of a given value.
END
Other examples
Create function Fun_EmployeeInformation()
returns table
as
return(select * from Employee )
Examples: User Defined Functions
create database exercise
use exercise
select dbo.NumberGrade('C')
Question2: define the function that calculates GPA
Use previously created function(numbergrade)
go
create function fn_GPA(@studID int)
returns float
as
begin
declare @TotalWeight float
declare @crHrs_sum float
declare @GPA float
Question2: define the function that calculates GPA
select @TotalWeight=(select
sum(dbo.numberGrade(stud_Grade.Grade )* CrHr) from stud_Grade
where studID=@studID)
select @crHrs_sum=(select SUM(crHr) from stud_Grade where studID
=@studID)
set @GPA=@TotalWeight/@crHrs_sum
return @GPA
end
go
Question2: Write one single function calculates GPA
go
create function GPA(@studID int)
returns float
as
begin
Question2: Write one single function calculates GPA
declare @TotalWeight float
declare @crHrs_sum float
declare @GPA float
select @TotalWeight =(select SUM((case Grade
when 'A' then 4*stud_Grade.CrHr
when 'B' then 3*stud_Grade.CrHr
when 'C' then 2*stud_Grade.CrHr
when 'D' then 1*stud_Grade.CrHr
when 'F' then 0 end ))
Question2: Write one single function calculates GPA
from stud_Grade where stud_Grade.studID =@studID)
select @crHrs_sum=(select SUM(stud_Grade.CrHr) from stud_Grade
where studID=@studID)
set @GPA=@TotalWeight/@crHrs_sum
return @GPA
end
go