Lecture3_DBP2024

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

LECTURE3

Functions in SQL Server


Functions in SQL Server
The Functions in SQL server broadly divided into 2
types
• Built-in function
• User-Defined Functions
BUILT-IN FUNCTIONS
Functions in SQL Server
What are Built-In Functions?
 In SQL Server a built-in function is a piece of code that takes one or
more inputs and returns a value.
 An example of a built-in function is ABS(), which when given a value
calculates the absolute (non-negative) value of the number.

Note: SQL built-in functions may or may not take parameters but always returns a value.
Functions in SQL Server
Built-in String Functions in SQL Server
Function Example Output
ASCII(Character_Expression) Select ASCII(‘A’) 65
LTRIM(Character_Expression) Select LTRIM(‘ Hello’) Hello
LOWER(Character_Expression) Select LOWER(‘CONVERT This String ’) convert this string
UPPER(Character_Expression) Select UPPER(‘CONVERT This String’ ) CONVERT THIS STRING
REVERSE(‘Any_String_Expression’) Select REVERSE(‘ABCDEFG’) GFEDCBA
LEN(String_Expression) Select LEN(‘ Functions ‘) 9
CHARINDEX(‘Find’, ‘Search’, Select CHARINDEX(‘@’,’hina@aaa.com’,1) 5
‘Start_Location’)
SUBSTRING(‘expression’, ‘Start’, Select SUBSTRING( ‘info@dotnettutorials.net’ dotnettutorials.net
‘Length’) ,6, 19)
Functions in SQL Server
Built-in other Functions
 Getting Information About Data.
 IsDate()
 IsNumeric()
 Functions for Handling null Values.
 IsNull()
 Conversion Functions.
 Cast (expression AS data_type)
 Convert(datatype [(length)], expression [, style])
 Functions for Handling Identity Values
 @@identity
Functions in SQL Server
Built-in Date and Time Functions
The following set of functions is designed to process data and time values and expressions.
Get (Current) Date GetDate() :It will return the system time in datetime format.
Extracting Parts of Date and Time. From time to time, just one component of the date and
time value will be extracted.
• DAY(date)
• MONTH(date)
• YEAR(date)
Date and Time Calculations Transact-SQL contains two functions for performing calculations
on date and time
 DateAdd(datepart, number, date)
 DateDiff(datepart, startdate, enddate)
Functions in SQL Server
Built-in Aggregate Functions
perform an operation on a set of records and return a single value. They can be used in the
following situations:
The selection list of the Select statement - A Having clause - A Compute clause

Function Description
Avg([All | Distinct] expression) Returns the average value in the group.
Count([All | Distinct] expression |*) Counts the number of items in the group.
Sum(expression) Returns the sum of the expression's values.
Max(expression) Returns the maximum value in the expression.
Min(expression) Returns the minimum value in the expression.
Functions in SQL Server
OVER Clause in SQL Server with Examples

Example: COUNT (Department) OVER (PARTITION BY Department)


• In the above example, the data will be partition by Department i.e. there will be
three partitions (IT, HR, and Payroll), and then the COUNT() function will be
applied to each partition. Here, you can use a wide range of built-in functions
such as COUNT(), SUM(), MAX(), ROW_NUMBER(), RANK(), DENSE_RANK(),
AVG(), MIN(), etc.
Functions in SQL Server
 Example: OVER clause in SQL Server
We need to generate a report to display the
total number of employees department-wise.
Along with this we also need to display the
Total Salary, Average Salary, Minimum Salary,
and Maximum Salary department wise. That
means we need to generate a report like below.
Functions in SQL Server
How can we achieve the desired output?
by using the OVER clause combined with the PARTITION BY clause as shown in
the below code.
SELECT Name, Salary, Department,
COUNT(Department) OVER(PARTITION BY Department) AS DepartmentTotals,
SUM(Salary) OVER(PARTITION BY Department) AS TotalSalary,
AVG(Salary) OVER(PARTITION BY Department) AS AvgSalary,
MIN(Salary) OVER(PARTITION BY Department) AS MinSalary,
MAX(Salary) OVER(PARTITION BY Department) AS MaxSalary
FROM Employees
USER DEFINED FUNCTIONS
Functions in SQL Server
Types of User-Defined Function:
In SQL Server, we can create three types of User-Defined Functions,
such as
 Scalar Valued Functions
 Inline Table-Valued Functions
 Multi-Statement Table-Valued Functions
Functions in SQL Server
I. SQL Server Scalar Valued Functions
 The user-defined function which returns only a single value (scalar
value) is known as the Scalar Valued Function.
 Scalar Value Functions in SQL Server may or may not have parameters
but always return a single (scalar) value.
 The returned value which is return by the SQL Server Scalar Function
can be of any data type, except text, ntext, image, cursor, and
timestamp..
Functions in SQL Server
 The syntax to create a user-defined scalar value function in SQL
server.

 Syntax for calling a Function in SQL Server:

SELECT dbo.<FunctionName>(Value)

SELECT <DataBaseName>.dbo.<FunctionName>(Value)
Functions in SQL Server
• Examples: Write a Scalar Function to get the date difference.
CREATE FUNCTION CalculateAge (@DOB DATE)
RETURNS INT
AS
BEGIN
DECLARE @AGE INT
SET @AGE = DATEDIFF(YEAR, @DOB, GETDATE())-
CASE
WHEN (MONTH(@DOB) > MONTH(GETDATE())) OR
(MONTH(@DOB) = MONTH(GETDATE()) AND
DAY(@DOB) > DAY(GETDATE()))
THEN 1
ELSE 0 --Calling the above function:
END SELECT dbo.CalculateAge ('02/29/1988')
RETURN @AGE SELECT dbo.CalculateAge ('02/29/1988') AS AGE
END
Functions in SQL Server
 Scalar Valued Function in Select Clause:
How can use CalculateAge(@DOB DATE) takes the DOB value from Employee
table and returns the Age .

SELECT ID, Name, DOB, dbo.CalculateAge(DOB)


AS Age
FROM Employee
Functions in SQL Server
 SQL Server Scalar Valued Function in Where Clause:

SELECT ID, Name, DOB, dbo.calculateAge(DOB) AS Age


FROM Employee
WHERE dbo.calculateAge(DOB) > 31
 To alter a function we use alter function FuncationName
 To delete a function we use drop function FuncationName
 To view the text of function you need to use sp_helptext FunctionName
Functions in SQL Server
 Can you use stored procedure for calculate Age ?
 Yes, A stored procedure can also accept the DOB of an employee and
return the age but we cannot use a stored procedure in a select
clause or where clause. This is one of the differences between a
function and a stored procedure.
Functions in SQL Server
II. Inline Table Valued Function in SQL Server
 An Inline Table-Valued function returns a table by using the RETURNS
TABLE statement.
 The body of the function will have only a Single Select Statement prepared with
the “RETURN” statement.
Functions in SQL Server
Example: Inline Table-Valued Function in SQL Server
1. Create a function that accepts
student id as input and returns
that student details from the table.
CREATE FUNCTION FN_GetStudentDetailsByID
(
@ID INT SELECT * FROM FN_GetStudentDetailsByID(2)
)
RETURNS TABLE
AS
RETURN (SELECT * FROM Student
WHERE ID = @ID)
Functions in SQL Server
2. Create a function to accept branch name as input and returns the list
of students who belongs to that branch.
CREATE FUNCTION FN_GetStudentDetailsByBranch
(
@Branch VARCHAR(50)
)
RETURNS TABLE
AS
RETURN (SELECT * FROM Student WHERE Branch =
@Branch)

SELECT * FROM FN_GetStudentDetailsByBranch('CSE')


Functions in SQL Server
• Where can we use Inline Table-valued Functions in SQL Server?
1. The Inline Table-Valued function in SQL Server can be used to
achieve the functionalities of parameterized views,
2. The table returned by the inline table-valued function in SQL Server
can also be used in joins with other tables.
Functions in SQL Server
III. Multi Statement Table Valued Function in SQL Server
 The Multi-Statement Table Valued Function in SQL Server is the same
as the Inline Table-Valued Function means it is also going to returns a
table as an output but with the few differences.
 The syntax of the Multi-Statement Table-Valued Function in SQL
Server.
Functions in SQL Server
 Example:

Let’s write both Inline and Multi-Statement Table-Valued functions in SQL Server
that return the following output.
Functions in SQL Server
-- Multi-statement Table Valued function:
CREATE FUNCTION MSTVF_GetEmployees()
RETURNS @Table Table (ID int, Name varchar(20), DOB Date)
AS
BEGIN
INSERT INTO @Table
SELECT ID, Name, Cast(DOB AS Date)
FROM Employee
Return
End -- Inline Table Valued function:
CREATE FUNCTION ILTVF_GetEmployees()
RETURNS TABLE
AS
RETURN (SELECT ID, Name, Cast(DOB AS Date) AS
DOB
FROM Employee)
Functions in SQL Server
SELECT * FROM dbo.MSTVF_GetEmployees()
--or
SELECT * FROM dbo.ILTVF_GetEmployees()

UPDATE MSTVF_GetEmployees() SET Name='Pranaya1'


WHERE ID= 1 --Not Allowed

UPDATE ILTVF_GetEmployees() SET Name='Pranaya1‘


WHERE ID= 1 -- Allowed
Functions in SQL Server
• What are the differences between Inline and Multi-Statement Table-
Valued Functions in SQL Server?
Inline Table-Valued Function Multi-Statement Table-Valued Function
The returns clause cannot define the structure of The returns clause defines the structure of the table
the table
cannot have BEGIN and END blocks has the Begin and End blocks.
It is possible to update the underlying database it is not possible to update the underlying database
table table
better for performance worst for performance
Functions in SQL Server
• What is the Difference Between Functions and Procedures in SQL
Server?
Procedures Functions
returning a value is optional Must return a value
have parameters of both input and output Have only input parameters.

can perform Select. Update, Insert and Delete Can only be used to perform select operations.
operations
provides the options to perform Transaction These operations are not possible in a function.
Management, Error Handling, etc.
We call a procedure using EXECUTE/ EXEC command A function is called by using SELECT command only.
From a procedure, we can call another procedure or A function we can call another function but not a
a function procedure.

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