DBMS - Lecture 7 Functions
DBMS - Lecture 7 Functions
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.
• 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;
• 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
• 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
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
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:
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
Use Function:
Select dbo.Age( dbo.Age('10/08/1982')
Calling Scalar Function
• 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