本以为sqlserver自带这种根据出生日期自动算年龄而且能精确到天的函数,结果上网找半天也没找到,只找到些能算到几岁的。就自己写了个。大神应该有一行代码搞定的办法,本人的能力只能千行才搞定-->-->
有更好办法的赶紧来嘲讽我吧。
declare @Age varchar(100),@now datetime, @birthYear int, @birthMonth int, @birthDay int,
@nowYear int,@nowMonth int,@nowDay int,@AgeMonth int,@BirthMonthMaxDays int,@lastBirth int
set @now=GETDATE()
set @birthYear=DateName(year,@dBirthday)
set @birthMonth=DateName(month,@dBirthday)
set @birthDay=DateName(day,@dBirthday)
set @nowYear=DateName(year,GetDate())
set @nowMonth=DateName(month,GetDate())
set @nowDay=DateName(day,GetDate())
set @lastBirth=DATEDIFF(year,@dBirthday,@now)
set @AgeMonth=DATEDIFF(MONTH, dateadd(year,@lastBirth-1,@dBirthday) ,@now)
set @BirthMonthMaxDays=cast(32-DAY(@dBirthday+32-DAY(@dBirthday)) as int)
if @now>=@dBirthday
begin
set @Age=
case when @lastBirth>0 then
(case when (@nowMonth>@birthMonth) then cast(@lastBirth as varchar)+'岁'
when ((@nowMonth=@birthMonth)and(@nowDay>=@birthDay)) then cast(@lastBirth as varchar)+'岁'
when @nowMonth<@birthMonth and(@lastBirth-1<>0) then cast(@lastBirth-1 as varchar)+'岁'
else ''
end)
else '' end +
ltrim(case when @nowMonth>@birthMonth then cast(@nowMonth-@birthMonth as varchar)+'个月'
when @nowMonth<@birthMonth and 11-@birthMonth+@nowMonth<>0 then cast(11-@birthMonth+@nowMonth as varchar)+'个月'
when @nowMonth=@birthMonth then case when @nowDay<@birthDay then '11个月' else''end
else ''end) +
case when @nowDay<@birthDay then cast(@BirthMonthMaxDays-@birthDay+@nowDay as varchar)+'天'
when @nowDay>@birthDay then cast(@nowDay-@birthDay as varchar) +'天'
else ''end
end
else
begin
set @Age='输入出生日期有误'
end
return @Age