0% found this document useful (0 votes)
4 views

Function in SQL

Uploaded by

mohamedapdo1212
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Function in SQL

Uploaded by

mohamedapdo1212
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

DBMS(II) Laboratory

Lab. 1: DateTime Functions and User Defined Functions

❖ Datetime Data Types in SQL Server:

Data Type Format


Time hh:mm:ss.nnnnnnn
Date YYYY-MM-DD
Smalldatetime YYYY-MM-DD hh:mm:ss
datetime YYYY-MM-DD hh:mm:ss.nnn
datetime2 YYYY-MM-DD hh:mm:ss.nnnnnnn

❖ The following functions can be used to get the current system date and time:

Function Date Time Format Description


GETDATE( ) 2020-07-15 17:50:33.230 Commonly used function
SYSDATETIME( ) 2020-07-15 17:50:33.2337083 More fractional seconds precision.

select getdate()
select SYSDATETIME()
❖ Some Usefull Datetime Functions:
1- ISDATE() - Checks if the given value, is a valid date, time, or datetime. Returns 1 for success, 0
for failure.
Select ISDATE('IT') -- returns 0
Select ISDATE(Getdate()) -- returns 1
Select ISDATE('2012-08-31 21:02:04.167') -- returns 1
2- Day() - Returns the 'Day number of the Month' of the given date
Select DAY(GETDATE()) -- Returns the day number of the month, based on current system
datetime.
Select DAY(2010-10-31) -- Returns 31
3- Month( ) - Returns the 'Month number of the year' of the given date.
Select Month(GETDATE( )) -- Returns the Month number of the year, based on the
current system date and time
Select Month('2010-10-31') -- Returns 10
4- Year() - Returns the 'Year number' of the given date.
Select Year(GETDATE( )) -- Returns the year number, based on the current system date
Select Year('2010-10-31') -- Returns 2010
5- DateName(DatePart,Date) - Returns a string, that represents a part of the given
date. 'DatePart' parameter specifies, the part of the date, we want.

1
Select DATENAME(Day, '2012-09-30 12:43:46.837') -- Returns 30
Select DATENAME(YEAR, '2012-09-30 12:43:46.837') -- Returns 2012
Select DATENAME(MONTH, '2012-09-30 12:43:46.837') -- Returns
September
Select DATENAME(HOUR, '2012-09-30 12:43:46.837') -- Returns 12
Select DATENAME(wk, '2012-09-30 12:43:46.837') -- Returns 40
➢ Valid Datepart parameter values are:

datepart Abbreviations
year yy, yyyy
month mm, m
day dd, d
week wk, ww
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns

6- 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

7- DATEDIFF(datepart,startdate,enddate) - Returns the count of the specified datepart


boundaries crossed between the specified startdate and enddate.

Examples:
Select DATEDIFF(MONTH,'2005-11-30','2006-01-31') -- returns 2
Select DATEDIFF(DAY,'2005-11-30','2006-01-31') -- returns 62
Select DATEDIFF(hh,'2005-11-30','2006-01-31') -- returns 1488

2
8-CAST: It is used to convert one data type to another in SQL server.

Syntax of CAST function from MSDN:


CAST ( expression AS data_type [(length)])
Examples:
select CAST( getdate() AS nvarchar)-- returns Jul 15 2020 7:23PM
select CAST('MALYSIAN UNIVERSITY' AS nvarchar(8))--returns MALYSIAN

Functions in SQL Server

➢ Two types of functions in SQL:


1- System Functions: Built-in functions found in SQL server and ready to use like aggregation
functions, string functions, datetime functions, math functions…etc.
2- User Defined Functions (UDF): Functions defined by the user of SQL server.
▪ Three types of UDF in SQL server:
1. Scalar functions
2. Inline table-valued functions
3. Multistatement table-valued 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
Examples:
select power(3,2) -- returns 9
select square(4) -- returns 16
➢ To create a function, we use the following syntax:
CREATE FUNCTION Function_Name (@Parameter1 DataType, @Parameter2
DataType,..@Parametern Datatype)
RETURNS Return_Datatype
AS
BEGIN
Function Body
Return Return_Parameter
END
➢ Consider the following Employee table:

3
id name Daily _Salary
1 Rami 6
2 Sam 7
3 Ahmed 5
4 Ali 8

QUSTION : Create a function which calculates and returns the factorial of a given number then use it to
compute the factorial of each Daily_salary in the above table .

create function fact(@number int)


returns int
as
begin
declare @fact int =1;
while @number>1
begin
set @fact=@fact *@number;
set @number=@number-1;
end
return @fact
end

How to call a Scalar UDF ?


▪ When calling a scalar user-defined function, you must supply a two-part
name, OwnerName and FunctionName.
▪ dbo stands for database owner.
Select dbo.fact (5)-- returns 120
✓ Scalar user defined functions can be used in the Select clause as shown below:
Select name, Daily_salary,dbo.fact (Daily_salary) as D_Salary_fact
from Employee

name daily_salary D_Salary_fact


Rami 6 720
Sam 7 5040
Ahmed 5 120
Ali 8 40320

✓ Scalar user defined functions can be used in the Where clause, as shown below:

4
QUESTION: Find the id and name of all employees whose factorial of their daily salary is less than
5000

Select id, name

from Employee
Where dbo.fact(Daily_salary)< 5000 ;

➢ important Notes:

1- To alter a function we use ALTER FUNCTION FuncationName .


2- To delete it, we use DROP FUNCTION FuncationName .
3-To view the text of the function, we use SP_HELPTEXT FunctionName
4- A stored procedure also can accept Daily_salary and return factorial, but you cannot use stored
procedures in a select or where clause.

Inline Table-Valued Functions:


We learnt that, a scalar function, returns a single value. on the other hand, an Inline Table Valued
function, return a table.
Syntax:
CREATE FUNCTION Function_Name(@Param1 DataType, @Param2 DataType...,
@ParamN DataType)
RETURNS TABLE
AS
RETURN (Select_Statement)

EX:
Create a function that returns EMPLOYEES details by GENDER from the table bellow .

CREATE FUNCTION fn_EmployeesByGender(@Gender nvarchar(10))


RETURNS TABLE
AS
RETURN (Select Id, Name, DateOfBirth, Gender, DepartmentId

5
from tblEmployees
where Gender = @Gender)

❖ Calling the Inline Table-Valued UDF:


Select *
from fn_EmployeesByGender('Male')
 Note:
Inline Table Valued functions can be used to achieve the functionality of parameterized views.

Home Work

1- Write the previous function fact using the stored procedure concept then execute it.
2- Write a user defined function that simulate the power system function in SQL Server for example:
power2(3,2) -- returns 9
3- Consider the following student table:

id S_name DateOfBirth
1 Maged 1994-01-24 02:30:20.260
2 Khalid 1985-01-20 19:10:20.280
3 Reham 2000-10-20 15:50:09.290
4 Sami 1992-04-25 09:30:20.390

- Create a function which calculates and returns the age of any student by using datetime functions
explained above when the date of birth is given then apply this function to find the name and age of all
the students.

Note: The result will be as follow:

S_name DateOfBirth age


Maged 1994-01-24 02:30:20.260 25 Years 4 Months 26 Days Old
Khalid 1985-01-20 19:10:20.280 34 Years 4 Months 30 Days Old
Reham 2000-10-20 15:50:09.290 18 Years 7 Months 30 Days Old
Sami 1992-04-25 09:30:20.390 27 Years 1 Months 25 Days Old

Eng. Maged Albadany

You might also like