Unit 2
Unit 2
Functions
Database Programming
Built-In Function Categories
String Functions
Mathematical / Numeric Functions
Date Functions
Other Functions
Security Functions
Conversion Functions
2
Built-In Function Categories
String Functions
SUBSTRING
UPPER , LOWER
LEFT, RIGHT
LEN
STUFF
REPLACE
ASCII
CHAR
CONCAT
CHARINDEX
PATINDEX
3
Built-In Function Categories
Mathematical / Numeric Functions
FLOOR
CEILING
ABS
POWER
ISNUMERIC
4
Built-In Function Categories
Date Functions
GETDATE
DATENAME
DATEPART
DAY
MONTH
YEAR
DATEDIFF
DATEADD
ISDATE
5
Built-In or System Functions
6
Built-In Function
Built-in function is a piece for programming that takes
zero or more inputs and returns a value
The inputs to a function are called parameters
Some functions have more than one others may not have any
Parameters are enclosed in parenthesis.
We use functions in the SELECT clause as well as
WHERE filter condition
A function can be used anywhere in a SELECT statement that
you can use an expression.
7
Deterministic & Nondeterministic
A function is said to be Deterministic or
Nondeterministic Function depending on whether it
returns the same or different value given the same set of
input values.
Deterministic functions always return the same result
Nondeterministic functions may return different results each
time they are called
Examples
Deterministic
DATEDIFF, ISNUMERIC, ISNULL
Nondeterministic
NEWID, NEWSEQUENTIALID
8
String Functions
SUBSTRING ( value_exp , start_exp , length_exp )
Extracts length_exp number of characters from value_exp
starting from start_exp
SELECT x = SUBSTRING('abcdef', 2, 3)
Returns bcd
UPPER ( character_expression )
Returns a character expression converted to uppercase
LOWER ( character_expression )
Returns a character expression converted to lowercase
9
String Functions (cont.)
LEFT ( character_expression , integer_expression )
Returns a specified no. of characters from the left part of a sting
RIGHT ( character_expression , integer_expression )
LEN ( string_expression )
Returns the number of characters of the specified string expression,
excluding trailing blanks
LTRIM(string_expression) | RTRIM(string_expression)
Returns a character expression after it removes leading / trailing
spaces
Examples
SELECT LEFT ( 'abcdef' , 2 ) -- Returns ab
SELECT LEN ( 'abcdef’ ) -- Returns 6
SELECT RTRIM( LTRIM(FName))
FROM Employee
10
String Functions (cont.)
STUFF( character_expression , start, length ,character_expression )
The STUFF function inserts a string into another string.
It deletes a specified length of characters in the first string at the start
position and then inserts the second string into the first string at the
start position
REPLACE ( string_expression1 , string_expression2 ,
string_expression3 )
Replaces all occurrences of a specified string value with another string
value
Examples
SELECT STUFF('abcdef', 2, 3, 'ijklmn’)
Returns -- aijklmnef
SELECT REPLACE('abcdefghicde','cde','xxx’)
Returns -- abxxxfghixxx
11
String Functions (cont.)
ASCII() Function
The ASCII() function returns the ASCII value for the specific
character.
Syntax
ASCII(character)
Examples: Return the ASCII value of the 1st character in "City" column
SELECT ASCII(City)
FROM Employee
Example 2: Return the ASCII value of a character
SELECT ASCII('c’) -- Returns 99
CHAR() Function
The CHAR() function returns the character based on the ASCII code
Example
SELECT CHAR(65) -- Returns A
12
String Functions (cont.)
STR ( float_expression [ , length [ , decimal ] ] )
The STR() function returns a number as a string.
Examples
SELECT STR(185.5) -- Returns 186
SELECT STR(185.476, 6, 2) - Returns 185.48
SELECT STR(185.476, 7, 4) - Returns 185.476
CONCAT() Function
The CONCAT() function adds two or more strings together.
Syntax
CONCAT(string1, string2, ...., string_n)
Example
SELECT CONCAT('SQL', ' is', ' fun!');
13
String Functions (cont.)
CHARINDEX() Function
CHARINDEX ( expToFind , expToSearch [ , startAt ] )
Examples
SELECT CHARINDEX ('h', 'Schools’) -- Returns 3
14
String Functions (cont.)
PATINDEX() Function
The PATINDEX() function returns the position of a pattern in a
string.
Syntax
PATINDEX(%pattern%, string)
15
Mathematical Functions
FLOOR ( numeric_expression )
Returns the largest integer less than or equal to the specified
numeric expression
CEILING ( numeric_expression )
ABS ( numeric_expression )
A mathematical function that returns the absolute (positive) value
of the specified numeric expression.
POWER ( float_expression , y )
Returns the value of the specified expression to the specified
power.
ISNUMERIC (expr)
Checks if an expression is a valid numeric type
16
Date Functions
GETDATE ( )
Returns the current date of the system
DATENAME ( datepart , date )
Returns a string that represents the datepart of the date
DATEPART ( datepart , date )
Returns an integer that represents the datepart of the date
DAY ( date )
Returns an integer that represents the day day part of the date
MONTH ( date )
Returns an integer that represents the month part of a date
YEAR ( date )
Returns an integer that represents the year part of a date
17
Date Functions - Examples
Return the current month name
SELECT DATENAME ( month , GetDate() )
Returns October
18
Date Functions (cont.)
DATEDIFF ( datepart , startdate , enddate )
Returns the number of date or time datepart boundaries that are
crossed between two specified dates
DATEADD (datepart , number , date )
Returns a new datetime value by adding an interval to the
specified datepart of the specified date
ISDATE ( expression )
Determines whether a datetime or smalldatetime input
expression is a valid date or time value.
19
Security Functions
CURRENT_USER
Returns the name of the current user. This function is equivalent
to USER_NAME().
SELECT CURRENT_USER
USER_ID
Returns the identification number for a database user.
SELECT USER_ID(‘dbo');
USER_NAME
Returns a database user name from a specified identification
number
Example
SELECT USER_NAME(4);
SELECT USER_NAME();
20
CAST & CONVERT
CAST
Converts a value of one type into another datatype
Syntax:
CAST ( expression AS data_type [ (length ) ])
CONVERT
Converts a value of one type into another datatype
Syntax:
CONVERT ( data_type [ ( length ) ] , expression )
21
Examples (CAST & CONVERT)
SELECT 9.5 AS Original
, CAST(9.5 AS int) AS int
, CAST(9.5 AS decimal(6,4)) AS decimal
22
Examples (CAST & CONVERT)
SELECT SUBSTRING(FName, 1, 3) AS EmpName, Salary
FROM Employee
WHERE CAST(Salary AS INT) LIKE '3%’
23
COALESCE
Returns the first non-null expression among its
arguments
At least one of the null values must be a typed NULL
Syntax:
COALESCE ( expression [ ,...n ] )
24
COALESCE - Example
Examples
25
COALESCE and CASE
The COALESCE expression is a syntactic shortcut for
the CASE expression
The following two expressions are equivalent
CASE
WHEN expr1 IS NOT NULL THEN expr1
ELSE expr2
END
26
More Functions
ISNULL Function
Syntax
ISNULL ( check_expression , replacement_value )
27
More Functions
NULLIF
Same as . . . . “Return NULL if they are equal”
Returns NULL if two expressions are equal, otherwise it returns
the first expression
Syntax
NULLIF(expr1, expr2)
Example
SELECT NULLIF(4,4) AS Same
, NULLIF(5,7) AS Different
28
More Functions
@@ERROR Function
@@IDENTITY Function
SCOPE_IDENTITY
IDENT_CURRENT, and
@@IDENTITY
@@ROWCOUNT Function
29
Exercise on Built-in Functions
Write a given name in the proper form (Capitalize 1st
letter )
Find the age of a person given the date of birth
Generate User names for each employee
Rule: First letter of the first name concatenated with the last
names
Extract the first name and last name from a given full
name
30