给个函数,计算年龄可以精确到天的,用法自己观察哈:---------------------------------------------------------------------- --计算年龄的函数 --算法原则:超过生日,年龄就得加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
与实际对照一下再调整就可以了
select datediff(year,出生日期,getdate()) as '年龄' from person如果没到生日是不是少算一岁?
我是这样计算年龄的,这样算出来比较合理。
--计算年龄的函数
--算法原则:超过生日,年龄就得加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