目标:根据出生日期计算当前的年龄
步骤:
1.创建测试用的表
create TABLE birthday_test
(
id int identity(1,1) PRIMARY key ,
name nvarchar(50) not null,
birthday datetime not null DEFAULT('2010-10-01')
)
2.当前日期是2020-04-24,往表中插入三条数据
INSERT into birthday_test VALUES ('张三','2010-04-23')
INSERT into birthday_test VALUES ('李四','2010-04-24')
INSERT into birthday_test VALUES ('王五','2010-04-25')
3.查询显示数据
SELECT * FROM birthday_test
4.依据字段birthday进行处理,查询当前年龄
方法一:
SELECT id,name,birthday,
CASE
WHEN datediff(dd, dateadd(yy, datediff(yy, birthday, getdate()), birthday), getdate()) < 0 THEN datediff(yy, birthday, getdate()) - 1
ELSE datediff(yy, birthday, getdate())
END as age
FROM birthday_test
备注:重要的语句是:CASE
WHEN datediff(dd, dateadd(yy, datediff(yy, birthday, getdate()), birthday), getdate()) < 0 THEN datediff(yy, birthday, getdate()) - 1
ELSE datediff(yy, birthday, getdate())
END as age ;百度上很多地方是除以365.25其实是不对的,因为闰年的原因导致不准确。比如:SELECT FLOOR(DATEDIFF(day, ‘2004-04-23’,‘2022-4-23’)/365.2422) as age1 ,计算的结果是17,实际应该是18岁了。
方法二
封装函数,直接调用计算,函数格式如下
if exists(select * from sysobjects where name = 'f_birthdayToAge')
drop FUNCTION f_birthdayToAge
GO
create function f_birthdayToAge --定义函数f_birthdayToAge
(@BirthDate datetime,@ThisDate datetime) --@BirthDate 第一个参数 datetime @ThisDate第二个参数 datetime
returns int --返回值类型
as
begin
declare @dtBirthDate datetime --定义出生日期
declare @dtThisDate datetime --定义当前日期
set @dtBirthDate = @BirthDate --给出生日期赋值
set @dtThisDate = @ThisDate --给当前日期赋值
declare @nYear int --定义年龄
select @nYear = datediff(yy, @dtBirthDate, @dtThisDate) --计算当前日期和出生日期的年份差值
select @nYear = case when datediff(dd, dateadd(yy, @nYear, @dtBirthDate), @dtThisDate) < 0 then @nYear - 1 else @nYear end --当前日期加上年份差值再和当前日期比较,如果小于当前日期,就把年份减去1,否则就取年份差值
return (@nYear) -- 返回年龄
end
函数调用:
SELECT dbo.f_birthdayToAge('2004-04-23','2022-4-23')