Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views

MS SQL Server Managment Functions - Section-3

This document provides information about functions in Microsoft SQL Server. It discusses two types of functions: system defined functions, which include scalar and aggregate functions for operations on single values or collections of values; and user defined functions, which include scalar valued functions that return a single value and table valued functions that return tables. Several examples of built-in functions are provided for mathematical operations, date/time operations, and string manipulation. The document also provides the syntax for creating user-defined scalar functions in SQL Server.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

MS SQL Server Managment Functions - Section-3

This document provides information about functions in Microsoft SQL Server. It discusses two types of functions: system defined functions, which include scalar and aggregate functions for operations on single values or collections of values; and user defined functions, which include scalar valued functions that return a single value and table valued functions that return tables. Several examples of built-in functions are provided for mathematical operations, date/time operations, and string manipulation. The document also provides the syntax for creating user-defined scalar functions in SQL Server.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Rahmatullah Khuram 6/4/2020 1

GAWHARSHAD University
Computer Science Department
5th Semester-1399

Subject: RDBMS II
Microsoft SQL Server Management
Lecturer: Rahmatullah Khuram

Rahmatullah Khuram 6/4/2020 2


Section -3

Unit -6
SQL Server Functions

Rahmatullah Khuram 6/4/2020 3


❑ Functions
Function is a Database object in MS SQL Server.
Basically, it is a set of SQL statements that accept
only input parameters, perform actions and return
the result. Function can return an only single value
or a table. We can’t use a function to Insert,
Update, Delete records in the Database table(s).
There are two different types of Functions in SQL
Server.
1. System Defined Functions
2. User Defined Functions
1. System Defined Functions
These functions are defined by SQL Server for a
different purpose. We have two types of system
defined function in SQL Server.
I. Scalar Function
Scalar functions operate on a single value and
return a single value. Below is the list of some
useful SQL Server Scalar functions.
You can use them along with DML (SELECT)
Statement while querying the information from
Database.
Scalar Function Description
abs(-10.67) This returns an absolute number of the given number
means 10.67.
rand(10) This will generate a random number of 10 characters.
round(17.56719,3) This will round off the given number to 3 places of
decimal means 17.567
upper('dotnet') This will returns the upper case of given string means
'DOTNET'
lower('DOTNET') This will returns the lower case of given string means
'dotnet'
ltrim(' dotnet') This will remove the spaces from the left-hand side of
'dotnet' string.
convert(int, 15.56) This will convert the given float value to integer means 15.
II. Aggregate Function
Aggregate functions operate on a collection of
values and return a single value. Below is the
list of some useful SQL Server Aggregate
functions. You can use them along with DML
(SELECT) Statement while querying the
information from Database.
Aggregate Description
Function
Max() This returns maximum value from a collection of values.
Min() This returns the minimum value from a collection of
values.
Avg() This returns an average of all values in a collection.
Count() This returns no of counts from a collection of values.
Sum() Allows you to calculate the sum of the values from the
specified columns in a set of rows.
❑ Date/Time Functions
The Date/Time functions operate on a
collection of date and time values and return a
single value. Below is the list of some useful
SQL Server Date and Time functions. You can
use them along with DML (SELECT) Statement
while querying the information from Database.
Please remember to know the Date and Time
data types before working with Date/Time
functions.
Data type Description Storage

datetime From January 1, 1753 to December 31, 9999 with an accuracy of 8 bytes
3.33 milliseconds
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 6-8
100 nanoseconds bytes
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 4 bytes
minute
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes

time Store a time only to an accuracy of 100 nanoseconds 3-5


bytes
datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10
bytes
timestamp Stores a unique number that gets updated every time a row gets
created or modified. The timestamp value is based upon an
internal clock and does not correspond to real time. Each table
may have only one timestamp variable
Date/Time Date/Time Format Description
Functions
GETDATE () 2020-06-01 18:27:01.487 Commonly Used
CURRENT_TIMESTA ANSI SQL Equivalent to
2020-06-01 18:27:01.487
MP GETDATE
2020-06-01 More Fractional Seconds
SYSDATETIME ()
18:27:01.4874261 Precisions
SYSDATETIMEOFFSE 2020-06-01 More Fractional Seconds
T () 18:27:01.4874261 + 04:30 Precisions+Off Set
GETUTCDATE () 2020-06-01 13:57:01.487 UTD Date and Time
UTC Date and Time with
2020-06-01
SYSUTCDATETIME () more Fractional Seconds
13:57:01.4874261
Precisions.
Examples
▪ SELECT GETDATE()
Returns: 2020-06-01 18:27:01.487
▪ SELECT CURRENT_TIMESTAMP
Returns: 2020-06-01 18:27:01.487
▪ SELECT SYSDATETIME ()
Returns: 2020-06-01 18:27:01.4874261
▪ SELECT SYSDATETIMEOFFSET ()
Returns: 2020-06-01 18:27:01.4874261 +04:30
▪ SELECT GETUTCDATE ()
Returns: 2020-06-01 13:57:01.487
▪ SELECT SYSUTCDATETIME()
Returns: 2020-06-01 13:57:01.4874261
❑ Mathematical Functions
Mathematical functions are very important in SQL
to implement different mathematical concepts in
queries.
Some of the major mathematical functions in SQL
are as follows:

▪ABS(X)
This function returns the absolute value of X. For
example:
Select abs(-6);
This returns 6.
▪ MOD(X,Y)
The variable X is divided by Y and their remainder is
returned. For example:
Select mod(9,5);
This returns 4.
▪ SIGN(X)
This method returns 1 if X is positive, -1 if it is negative and
0 if the value of X is 0. For example:
Select sign(10);
This returns 1.
▪ FLOOR(X)
This returns the largest integer value that is either less than
X or equal to it. For example:
Select floor(5.7);
This returns 5.
▪ CEILING(X)
This returns the smallest integer value that is either more
than X or equal to it. For example:
Select ceiling(5.7);
This returns 6.
▪ POWER(X,Y)
This function returns the value of x raised to the power of Y
For example:
Select power(2,5);
This returns 32.
▪ ROUND(X)
This function returns the value of X rounded off to the whole
integer that is nearest to it. For example:
Select round(5.7);
This returns 6.
▪ SQRT(X)
This function returns the square root of X. For example:
Select sqrt(9);
This returns 3.
▪ ASIN(X)
This function accepts a Sin value as the input and returns
the angle in radians. For example:
Select asin(0);
This returns 0.
▪ ACOS(X)
This function accepts a Cos value as the input and returns
the angle in radians. For example:
Select acos(1);
This returns 0.
❑ String Functions
The string functions are used primarily for
string manipulation. There are many types of
string functions in SQL server but the following
details the important string functions which are
in SQL Server.
▪ ASCII ()
The following example returns the ASCII code values of the
character A and Z:
Select ASCII(‘A’);
This returns 65
▪ CHAR()
This function returns the character of the numbers :
Select CHAR(65);
This returns A.
▪ LEFT()
This function extract a given number of character from the left side
of a supplied string.
Select Left (‘input string’ , number of character);
Select left (‘ SQL Server’,3)
This returns SQL.
▪ RIGHT ()
This function extract a given number of character from the right side of a
supplied string:
Select Right (‘input string’ , number of character);
Select Right (‘ SQL Server’,6)
This returns SERVER
▪ REPLACE()
This function replace all occurrences of a substring with a new substring:
Select REPLACE(‘Input String’,’Substring’,’New String’);
Select REPLACE(‘MS SQL SERVER IS TO DIFFICULT TO
LEARN’,’DIFFICULT’,’EASY)
This returns MS SQL SERVER IS TO EASY TO LEARN.
▪ REPLICATE()
This function repeats a string a specified number of times.
Select REPLICATE (‘input string’ Count);
Select left (‘ SQL Server’,3)
This returns SQL SERVER SQL SERVER SQL SERVER.
▪ RTRIM ()
This function returns string after truncating the trailing
blanks.
Select RTITM (‘input string ‘);
Select Right (‘ SQL SERVER ‘)
This returns SQL SERVER
▪ STUFF()
This function deletes a part of a string and then inserts
a substring into the string, beginning at the specified
position.
STUFF (Input String, Start Position, length, replace with
substring)
Select STUFF (‘SQL Tutorial’,1,3, ‘SQL Server’)
This returns SQL Server Tutorial.
2. User Defined Functions
These functions are created by the user in the
system database or in a user-defined database.
There are two types of user-defined functions.
I. Scalar Valued Functions
II. Table Valued Functions
I. Scalar Valued Functions
The user-defined scalar function also returns a
single value as a result of actions performed by the
function. We can return any datatype value from a
function.
The scalar functions help you simplify your code.
For example, you may have a complex calculation
that appears in many queries. Instead of including
the formula in every query, you can create a scalar
function that encapsulates the formula and uses it
in each query. can find it under Programmability >
Functions > Scalar-valued Functions.
Syntax:
CREATE FUNCTION <FUNCTION_NAME>(@<PARAMETER
NAME><DATATYPE>[SIZE],......)
RETURNS <RETURN PARAMETER/VARIABLE DATATYPE>
AS
BEGIN
<FUNCTION BODY / STATEMENTS>;
RETURN <RETURN PARAMETER / VARIABLE NAME>
END

To call the Function use below syntax:

SELECT dbo.<FUNCTION_NAME> (VALUES)


❑ In the Syntax:
▪ First, specify the name of the function after the
CREATE FUNCTION keywords. The schema name
is optional. If you don’t explicitly specify it, SQL
Server uses dbo by default.
▪ Second, specify a list of parameters surrounded
by parentheses after the function name.
▪ Third, specify the data type of the return value in
the RETURNS statement.
▪ Finally, include a RETURN statement to return a
value inside the body of the function.
Example:
CREATE A SCALAR FUNCTION TO INPUT EMPLOYEE
ID AS A PARAMETER AND RETURNS THAT
EMPLOYEE’S GROSS SALARY BASED ON THE
FOLLOWING CONDITIONS.

COND1: BONUS 10%


COND2: OVERTIME 20%
COND3: TRANSPORATION 10%

TO FIND THE GROSS SALARY OF THE EMPLOYEE


To solve the question using the given
conditions we will create a table having
following values.
EID ENAME SALARY
100 AA 25000
101 BB 15000
102 CC 20000
103 DD 24000
Function
CREATE FUNCTION F_GRSAL (@EID INT)
RETURNS MONEY
AS
BEGIN
DECLARE @BASIC MONEY, @BONUS MONEY, @OVER MONEY,
@TRANS MONEY, @GROSS MONEY
SELECT @BASIC=SALARY FROM EMP2 WHERE EID=@EID
SET @BONUS=@BASIC *0.1
SET @OVER=@BASIC *0.2
SET @TRANS=@BASIC*0.3
SET @GROSS=@BASIC+@BONUS+@OVER+@TRANS
RETURN @GROSS
END
TO CALL THE FUNCTION
SELECT DBO.F_GRSAL (102)
❑ Removing a scalar function
To remove an existing scalar function, you use
the DROP FUNCTION statement:
Syntax:
Drop Function [schema_name.]function_name;

Example:
Drop Function F_GRSAL
II. Table Valued Functions
The user-defined table valued functions returns a
table variable as a result of actions performed by
the function. The value of the table variable should
be derived from a single SELECT statement. Or the
table valued functions returns more than one
values or more than one column from the tables.
Or, a table-valued function is a user-defined
function that returns data of a table type. The
return type of a table-valued function is a table,
therefore, you can use the table-valued function
just like you would use a table.
Syntax:
CREATE [OR ALTER] FUNCTION
<FUNCTION_NAME> (@<PARMAETER NAME>
<DATATYPE> [SIZE],....)
RETURNS TABLE
AS
RETURN (<SELECT QUERY / STATEMENT>)

Syntax to call the Function:


SELECT * FROM <FUNCTION NAME>(VALUE /
VALUES)
The syntax is similar to the one that creates a
user-defined function.
The RETURNS TABLE specifies that the function
will return a table. As you can see, there is no
BEGIN...END statement. The statement simply
queries data from the given table.
Once the table-valued function is created, you
can find it under Programmability > Functions
> Table-valued Functions.
Example:
Create a table valued function to accept the
table Department name as a parameter and
returns the list of the employees who are
working under that given department name.
In order to solve the question let’s consider an
employee table having EID, ENAME, SALARY
and DEPTNAME columns. With records
Employee Table

EID ENAME SALARY DEPTNAME


101 AA 20000 HR
102 BB 21000 IT
103 CC 40000 HR
104 DD 22000 FIN
105 EE 45000 IT
106 FF 33000 HR
107 GG 55000 FIN
108 TT 44000 IT
109 RR 12000 FIN
110 PP 34000 HR
Using the given syntax we can write the
function as follows:
Function
CREATE FUNCTION TVF1(@DEPTNAME NCHAR
(10))
RETURNS TABLE
AS RETURN (SELECT * FROM EMPLOYEE WHERE
DEPTNAME =@DEPTNAME).
Calling the Function
SELECT * FROM TVF1(‘HR')
Example2:
Create a function to call the values for the employees
whose salaries are greater than 20000. using the
employee table recently created.

Function:
CREATE FUNCTION TVF2()
RETURNS TABLE
AS
RETURN (SELECT * FROM EMPLOYEE WHERE SAL >
20000)

Calling the Function:


SELECT * FROM TVF2()
❑ Removing a table_valued function
To remove an existing table_valued function,
you use the DROP FUNCTION statement:
Syntax:
Drop Function [schema_name.]function_name;

Example:
Drop Function TVF1

You might also like