You are on page 1of 47

Function

Functions
• A user-defined function is a Transact-SQL or common language
runtime (CLR) routine that accepts parameters, performs an
action, such as a complex calculation, and returns the result of
that action as a value.

Functions/procedures can be written in SQL itself, or in an external


programming language.
• Functions are particularly useful with specialized data types
such as images and geometric objects.
– Example: functions to check if polygons overlap, or to
compare images for similarity.
• Some database systems support table-valued functions, which
can return a relation as a result.
Functions
The return value can either be a scalar (single) value or a table. Use this
statement to create a reusable routine that can be used in these ways:

• In Transact-SQL statements such as SELECT


• In applications calling the function
• In the definition of another user-defined function
• To parameterize a view or improve the functionality of an indexed
view
• To define a column in a table
• To define a CHECK constraint on a column
• To replace a stored procedure
• Use an inline function as a filter predicate for a security policy
Categories of Functions
Functions in SQL server can be broadly divided into 2 categories
1. Built-in functions
2. User Defined functions
Ranking
• Ranking is done in conjunction with an order by specification.
• Suppose we are given a relation
student_grades(ID, GPA)
giving the grade-point average of each student

• Find the rank of each student.


select ID, rank() over (order by GPA desc) as s_rank
from student_grades

• An extra order by clause is needed to get them in sorted order


select ID, rank() over (order by GPA desc) as s_rank
from student_grades order by s_rank

• Ranking may leave gaps: e.g. if 2 students have the same top GPA, both
have rank 1, and the next rank is 3
– dense_rank does not leave gaps, so next dense rank would be 2
Ranking Cont.
• Ranking can be done using basic SQL aggregation, but resultant query is very inefficient
select ID, (1 + (select count(*)
from student_grades B
where B.GPA > A.GPA)) as s_rank
from student_grades A
order by s_rank;

Ranking can be done within partition of the data.


• “Find the rank of students within each department.”
select ID, dept_name,
rank () over (partition by dept_name order by GPA desc)
as dept_rank from dept_grades
order by dept_name, dept_rank;

• Multiple rank clauses can occur in a single select clause.


• Ranking is done after applying group by clause/aggregation
Ranking Cont.
• Find the rank of each student
Solution:
select ID, rank() over (order by GPA desc) as s_rank from dept_grades
Output:

• “Find the rank of students within each department.”


Solution:
select id, dept_name, rank () over (partition by dept_name order by GPA
desc) as dept_rank from dept_grades order by dept_name, dept_rank;
Output:
Windowing
Window functions belong to a type of function known as a ‘set function’, which
means a function that applies to a set of rows. The word ‘window’ is used to
refer to the set of rows that the function works on.
 
Used to smooth out random variations.
E.g., moving average: “Given sales values for each date, calculate for each date
the average of the sales on that day, the previous day, and the next day”

Window specification in SQL:


Given relation sales(date, value)
select IName, sum(sizeSF) over (order by IName rows 1 preceding)
from location

select TID, sum(Salary) over (order by TID ROWS BETWEEN 1 preceding


and 1 following ) from teacher
Windowing Cont.
• between rows unbounded preceding and current
• rows unbounded preceding
• range between 10 preceding and current row
– All rows with values between current row value –10 to current value
• range interval 10 day preceding
– Not including current row

“Find total balance of each account after each transaction on the


account”
select account_number, date_time, sum (value) over (partition by
account_number order by date_time rows unbounded preceding) as
balance from transaction order by account_number, date_time
Windowing Cont.
• Can do windowing within partitions
• E.g., Given a relation transaction (account_number, date_time, value),
where value is positive for a deposit and negative for a withdrawal
– “Find total balance of each account after each transaction on the
account”
select account_number, date_time,
sum (value) over
(partition by account_number
order by date_time
rows unbounded preceding)
as balance
from transaction
order by account_number, date_time
Built in String functions
Built in String functions
• ASCII(Character_Expression): Returns the ASCII code of the given
character expression. To find the ACII Code of capital letter 'A'
Example: Select ASCII('A')
Output: 65
• CHAR(Integer_Expression): Converts an int ASCII code to a character. (the
Integer_Expression, should be between 0 and 255.)
• The following SQL, prints all the characters for the ASCII values from o
through 255
Declare @Number int
Set @Number = 1
While (@Number <= 255)
Begin
Print CHAR(@Number)
Set @Number = @Number + 1
End
Built in String functions Cont.

Declare @a int Declare @a int


set @a=65 set @a=1
while(@a<=90) while(@a<5)
Begin Begin
print char( @a) select Tid from Teacher
set @a=@a+1 print @a
end set @a=@a+1
end
String functions Example Cont.
LTRIM():
select LTRIM (' hello ')
select LTRIM(FirstName ) from Teacher
 
select RTRIM(FirstName )from Teacher
 
select LTRIM(firstname ), LastName, RTRIM (LTRIM (firstName ) ) +' '+ lastname as
fullName from Teacher
 
UPPER() & LOWER():
select UPPER(firstname ), LOWER (LastName) from Teacher
 
REVERSE():
select REVERSE (LastName) as ReverseLastName,lastname from Teacher
 
LEN():
select LEN (LastName) as ReverseLastName,lastname from Teacher
String functions Example Cont.
• Convert ():
– Select id, dept_name, date, convert ( varchar(11), date ) as
convertedDOB from dept_grades

• Type Calsting:
• Cast ( ):
– select cast(Salary as varchar) from Teacher
LEFT, RIGHT functions
• LEFT(Character_Expression, Integer_Expression) - Returns the
specified number of characters from the left hand side of the given
character expression.
Example: Select LEFT('ABCDE', 3)
Output: ABC

• RIGHT(Character_Expression, Integer_Expression) - Returns


the specified number of characters from the right hand side of the
given character expression.
Example: Select RIGHT('ABCDE', 3)
Output: CDE
CHARINDEX, SUBSTRING functions
• CHARINDEX('Expression_To_Find', 'Expression_To_Search',
'Start_Location')
– Returns the starting position of the specified expression in a
character string.
Select CHARINDEX ('@', 'sara@aaa.com', 1)
Output: 5

• SUBSTRING('Expression', 'Start', 'Length')


– As the name, suggests, this function returns substring (part of the
string), from the given expression.
Select SUBSTRING('John@bbb.com',6, 7)
Output: bbb.com
Replicate, Space functions
• REPLICATE(String_To_Be_Replicated,Number_Of_Times_To_Replicate )
– Repeats the given string, for the specified number of times.

Example: SELECT REPLICATE('Pragim', 3)


Output: Pragim Pragim Pragim

• SPACE(Number_Of_Spaces)
– Returns number of spaces, specified by the Number_Of_Spaces
argument. Example: The SPACE(5) function, inserts 5 spaces between
FirstName and LastName

Select FirstName + SPACE(5) + LastName as FullName From tblEmployee


Patindex functions
• PATINDEX('%Pattern%', Expression)
– Returns the starting position of the first occurrence of a pattern in a
specified expression
Example:
Select Email, PATINDEX ('%@aaa.com', Email) as FirstOccurence from
tblEmployee Where PATINDEX ('%@aaa.com', Email) > 0
Output:.
Replace functions
• REPLACE(String_Expression, Pattern , Replacement_Value)
– Replaces all occurrences of a specified string value with another
string value.

Example: All .COM strings are replaced with .NET


Select Email, REPLACE(Email, '.com', '.net') as ConvertedEmail from
tblEmployee
Mathematical functions
• ABS ( numeric_expression ):
– ABS stands for absolute and returns, the absolute (positive)
number.
Example:
Select ABS(-101.5) -- returns 101.5, without the - sign.

• CEILING (numeric_expression) and FLOOR (numeric_expression):


– CEILING and FLOOR functions accept a numeric expression as a
single parameter.
Examples:
Select CEILING(15.2) -- Returns 16
Select CEILING(-15.2) -- Returns -15
Select FLOOR(15.2) -- Returns 15
Select FLOOR(-15.2) -- Returns -16
Mathematical functions Cont.
• Power(expression, power):
– Returns the power value of the specified expression to the
specified power.
Example:
The following example calculates '2 TO THE POWER OF 3' = 2*2*2
= 8 Select POWER(2,3) -- Returns 8
• RAND([Seed_Value]):
– Returns a random float number between 0 and 1.

– If you want to generate a random number between 1 and 100,


– RAND() and FLOOR() functions can be used as shown below.
Every time, you execute this query, you get a random number
between 1 and 100.
– Select FLOOR(RAND() * 100)
Mathematical functions Cont.
• Insert Random Data in Table
• The following query prints 10
random numbers between 1 and Declare @id int
100.
set @id=1
while(@id<=10000)
Declare @Counter INT
Begin
Set @Counter = 1
insert into Temp values ('Product
While(@Counter <= 10)
Begin -'+ cast(@id as varchar(20)),
Print FLOOR(RAND() * 100) 'Product -' + cast(@id as
Set @Counter = @Counter + 1 varchar(20)) + ' Description')
End print @id
set @id=@id+1
end
Mathematical functions Cont.
• SQUARE ( Number ) –
– Returns the square of the given number.
Example:
Select SQUARE(9) -- Returns 81

• SQRT ( Number ) - SQRT stands for Square Root.


– This function returns the square root of the given value.

Example:
Select SQRT(81) -- Returns 9
DateTime functions
• Date Time data type
DateTime functions
• There are several built-in DateTime functions available in SQL
Server. All the following functions can be used to get the current
system date and time, where you have sql server installed.
DateTime functions Cont.
• ISDATE() –
– Checks if the given value, is a valid date, time, or datetime.
– Returns 1 for success, 0 for failure.
Select ISDATE('2012-08-31 21:02:04.167') -- returns 1
• Day() –
– Returns the 'Day number of the Month' of the given date
Select DAY('01/31/2012') -- Returns 31

• Month() –
– Returns the 'Month number of the year' of the given date
Select Month('01/31/2012') -- Returns 1
• Year() –
– Returns the 'Year number' of the given date
Select Year('01/31/2012') -- Returns 2012
DateTime functions Cont.
• DatePart(DatePart, Date)
– Returns an integer representing the specified DatePart.
Examples:
Select DATEPART(weekday, '2012-08-30 19:45:31.793') -- returns 5
Select DATENAME(weekday, '2012-08-30 19:45:31.793') -- returns
Thursday

• DATEADD (datepart, NumberToAdd, date)


– Returns the DateTime, after adding specified NumberToAdd, to the
datepart specified of the given date.
Examples:
Select DateAdd(DAY, 20, '2012-08-30 19:45:31.793') -- Returns 2012-09-19
19:45:31.793
Select DateAdd(DAY, -20, '2012-08-30 19:45:31.793') -- Returns 2012-08-10
19:45:31.793
• DATEDIFF(datepart, startdate, enddate)
– Returns the count of the specified datepart boundaries crossed between
the specified startdate and enddate.
Examples:
Select DATEDIFF(MONTH, '11/30/2005','01/31/2006') -- returns 2
Select DATEDIFF(DAY, '11/30/2005','01/31/2006') -- returns 62

DATENAME(DATEPART, DATE ):
• Example:
select DATENAME(day,'2016-08-01 01:51:04:911')
select DATENAME(WEEKDAY,'2016-08-01 01:51:04:911')
select DATENAME(MONTH,'2016-08-01 01:51:04:911')
 select id,dept_name,
DATENAME(WEEKDAY,date) as [Day],
DATENAME(MONTH,date) as [MONTH],
DATENAME(YEAR,date) as [YEAR]
from dept_grades
User Defined functions
• Like functions in programming languages, SQL Server user-defined
functions are routines that accept parameters, perform an action,
such as a complex calculation, and return the result of that action as
a value. The return value can either be a single scalar value or a
result set.
Why use them?
• They allow modular programming.
– You can create the function once, store it in the database, and call it any
number of times in your program. User-defined functions can be
modified independently of the program source code.
• They allow faster execution.
– Similar to stored procedures, Transact-SQL user-defined functions
reduce the compilation cost of Transact-SQL code by caching the plans
and reusing them for repeated executions
• They can reduce network traffic.
– An operation that filters data based on some complex constraint that
cannot be expressed in a single scalar expression can be expressed as a
function. The function can then invoked in the WHERE clause to reduce
the number or rows sent to the client.
User Defined functions
• In SQL Server there are 3 types of User Defined functions
1. Scalar functions
2. Inline table-valued functions
3. Multistatement table-valued functions
1. Scalar functions
• Scalar functions may or may not have parameters, but always return
a single (scalar) value.
• The returned value can be of any data type, except text, ntext,
image, cursor, and timestamp.
• A Scalar UDF can accept 0 to many input parameter and will return
a single value.
• Text, ntext, image and timestamp data types are not supported.
These are the type of user-defined functions that most developers
are used to in other programming languages.
Scalar functions Syntax
To create a function, we use the following syntax:

CREATE FUNCTION Function_Name (@Parameter1 DataType,


@Parametern Datatype )
RETURNS Return_Datatype
AS
BEGIN
Function Body

Return Return_Datatype
END
Scalar Function Example
create Function CalculateSalary(@Salary float)
returns float
as
begin
declare @maxSalary float
set @maxSalary = max(@Salary)*100
return @maxSalary
end

Call that function:


select dbo.CalculateSalary (30000)
Scalar Function Example
CREATE FUNCTION Age (@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
END
RETURN @Age
END

Use Function:
Select dbo.Age( dbo.Age('10/08/1982')
Calling Scalar Function

• Select Name, DateOfBirth, dbo.Age(DateOfBirth) as Age


from tblEmployees

• Select Name, DateOfBirth, dbo.Age(DateOfBirth) as Age


from tblEmployees Where dbo.Age(DateOfBirth) > 30
2.  Inline Table-Valued User-Defined
Function
• An inline table-valued function returns a variable of data type table
whose value is derived from a single SELECT statement.
• Since the return value is derived from the SELECT statement, there
is no BEGIN/END block needed in the CREATE FUNCTION
statement.
• There is also no need to specify the table variable name (or column
definitions for the table variable) because the structure of the
returned value is generated from the columns that compose the
SELECT statement.
Inline table valued functions
• A scalar function, returns a single value.
on the other hand,
• an Inline Table Valued function, return a table.

Syntax for creating an inline table valued function

CREATE FUNCTION Function_Name(@Param1 DataType,@ParamN DataType)


RETURNS TABLE
AS
RETURN (Select_Statement)
Inline table valued functions Example

• Create a function that returns EMPLOYEES by GENDER.

CREATE FUNCTION fn_EmployeesByGender( @Gender nvarchar(10))


RETURNS TABLE
AS
RETURN (Select Id, Name, DateOfBirth, Gender, DepartmentId
from tblEmployees where Gender = @Gender)

Calling the user defined function


Select * from fn_EmployeesByGender('Male')
Inline table valued functions Example
3. Multi-statement Table-Valued User-
Defined Function
• A Multi-Statement Table-Valued user-defined function returns a
table.
• It can have one or more than one T-Sql statement.
• Within the create function command you must define the table
structure that is being returned.
• After creating this type of user-defined function, we can use it in
the FROM clause of a T-SQL command unlike the behavior found
when using a stored procedure which can also return record sets.
Multi-statement Table-Valued Example
CREATE FUNCTION GetAuthorsByState ( @state char(50) )
RETURNS
@AuthorsByState table ( au_id Varchar(11), au_fname Varchar(20))
AS
BEGIN
INSERT INTO @AuthorsByState
SELECT  au_id, au_fname FROM Authors WHERE state = @state
 
IF @@ROWCOUNT = 0
BEGIN
INSERT INTO @AuthorsByState VALUES ('','No Authors
Found')
END
 
RETURN
Multi-statement Table-Valued Example
Cont.
• Example: In this example we are creating a Multi-Statement Table-Valued
function GetAuthorsByState which accepts state as the
input parameter and returns author id and firstname of all the authors
belonging to the input state.
• If for the input state there are no authors then this UDF will return a record
with no au_id column value and firstname as ‘No Authors Found’.

• We can use the below statements to get all the authors in the given input
state:
• SELECT * FROM GetAuthorsByState('CA')
• SELECT * FROM GetAuthorsByState('XY')
Difference between Inline Function & Multi
Value Function

You might also like