34,588
社区成员
发帖
与我相关
我的任务
分享
----------------------------------------------------------------------
--计算年龄的函数
--算法原则:超过生日,年龄就得加1
--
--SELECT dbo.FUN_GetAge('1988-7-29', getdate()) as age
----------------------------------------------------------------------
CREATE function [dbo].[FUN_GetAge]
(
@birthday datetime, --出生日期
@today datetime --截至日期
)
returns int
as
begin
if @birthday > @today
begin
return 0;
end
declare @age int
select @age = datediff(year, @birthday, @today)--年份差值
if datepart(month, @today) > datepart(month, @birthday)--月份超过
begin
select @age = @age + 1
end
if datepart(month, @today) = datepart(month, @birthday)--月份一样
begin
if datepart(day, @today) >= datepart(day, @birthday)--日超过
begin
select @age = @age + 1
end
end
return @age ;
End
select datediff(year,出生日期,getdate()) as '年龄' from person