Создание таблицы для функции
--Create table--
create table EmployeesWithDates
(
Id nvarchar(2),
Name nvarchar(20),
DateOfBirth datetime
)
insert into EmployeesWithDates (Id, Name, DateOfBirth)
values (1, 'Sam', '1980-12-30 00:00:00.000')
insert into EmployeesWithDates (Id, Name, DateOfBirth)
values (2, 'Pam', '1982-09-01 12:02:36.260')
insert into EmployeesWithDates (Id, Name, DateOfBirth)
values (3, 'John', '1985-08-22 12:03:30.370')
insert into EmployeesWithDates (Id, Name, DateOfBirth)
values (4, 'Sara', '1979-11-26 12:59:30.670')
Создание функции
--Create function--
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
Использование
--Use function--
select dbo.fnComputeAge('01/01/1900')