Function SQL Server
Funktsioon kasutab return – tagastab väärtused ja funksiooni saame kasutada SELECT lause sees.
create function fnComputeAge(@DOB datetime)
returns nvarchar(50)
as begin
declare @tempdate datetime, @years int, @months int, @days int
select @tempdate = @DOB
select @years = datediff(year, @tempdate, getdate()) - case when (month(@DOB) > month(GETDATE())) or (MONTH(@DOB)
= month (getdate()) and day(@DOB) > DAY(getdate())) then 1 else 0 end
select @tempdate = dateadd(year, @years, @tempdate)
select @months = datediff(month, @tempdate, getdate()) - case when day(@DOB) > day(getdate()) then 1 else 0 end
select @tempdate = dateadd(MONTH, @months, @tempdate)
select @days = datediff(day, @tempdate, getdate())
declare @Age nvarchar(50)
set @Age = cast(@years as nvarchar(4)) + ' Years ' + cast(@months as nvarchar(2)) +
' Months ' + cast(@days as nvarchar(2)) + ' Days old'
return @Age
end

select Id, Name, DateOfBirth, dbo.fnComputeAge(DateOfBirth)
as Age from EmployeesWithDates

INSERT INTO EmployeesWithDates (Id, Name, DateOfBirth)
VALUES (5, 'Lev', '2008-07-25')

select Id, Name, DateOfBirth,
convert(nvarchar, DateOfBirth, 109) as ConvertedDOB
from EmployeesWithDates

create function dbo.CalculateAge(@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

select Id, dbo.CalculateAge(DateOfBirth) as Age from EmployeesWithDates
where dbo.CalculateAge(DateOfBirth) > 16

-- inline table valued functions
alter table EmployeesWithDates
add DepartmentId int
alter table EmployeesWithDates
add Gender nvarchar(10)
update EmployeesWithDates set Gender = 'Male', DepartmentId = 1
where Id = 1
update EmployeesWithDates set Gender = 'Female', DepartmentId = 2
where Id = 2
update EmployeesWithDates set Gender = 'Male', DepartmentId = 1
where Id = 3
update EmployeesWithDates set Gender = 'Female', DepartmentId = 3
where Id = 4
update EmployeesWithDates set Gender = 'Male', DepartmentId = 4
where Id = 5
insert into EmployeesWithDates (Id, Name, DateOfBirth, DepartmentId, Gender)
values (6, 'Todd', '1978-11-29 12:59:30.670', 1, 'Male')
select * from EmployeesWithDates

create function fn_EmployeesByGender(@Gender nvarchar(10))
returns table
as
return (select Id, Name, DateOfBirth, DepartmentId, Gender
from EmployeesWithDates
where Gender = @Gender)
