欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

探讨如何计算age的sql函数

程序员文章站 2024-02-20 09:18:22
复制代码 代码如下:alter function [dbo].[get_fullage](  @birthday datetime, @currentday da...
复制代码 代码如下:

alter function [dbo].[get_fullage]
(
 @birthday datetime, @currentday datetime
)
returns int
as
begin
declare @age int
set @age = datediff(year, @birthday, @currentday)
if datediff(day, dateadd(year, @age, @birthday), @currentday) <= 0
 set @age = @age - 1
if datepart(month, @birthday) = 2 and datepart(day, @birthday) = 29 and datepart(month, @currentday) = 3
 and datepart(day, @currentday) = 1 and
 not (year(@currentday) % 4 = 0 and (year(@currentday) % 100 !=0 or year(@currentday) % 400 = 0))
 set @age = @age - 1
if @age < 0
 set @age = 0
  return @age
end

--sql根据出生日期计算age(不是很准确)
1.  select datediff(year,emp_birthday,getdate()) as '年龄' from  employeeunchangeinfo
2.  floor((datediff(day,u.emp_birthday,getdate()))/365