34,594
社区成员
发帖
与我相关
我的任务
分享
----------------------------------------------------------------------
--计算年龄的函数
--算法原则:超过生日,年龄就得加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
if OBJECT_ID('worker') is not null
drop table worker
go
--worker(workerno,workername,workersex,workerborndate)
create table worker(
workerno int,
workername varchar(20),
workersex int,
workerborndate datetime
)
insert into worker
select 3,'pjl',1,'1987-11-02' union all
select 2,'kzd',1,'1988-11-11' union all
select 1,'dyx',1,'1986-01-11'
select * from worker
select workerno,workername,workersex,DATEDIFF(MONTH,workerborndate,GETDATE())/12 as age
from worker
order by workerno
/*
select workerno,
workername,
workersex,
age=datediff(year,workerborndate,getdate())
from worker
order by workerno asc
select workerno,workername,workersex,datediff(year,workerborndate,getdate())+1 as age
from worker
order by workerno
select workerno,workername,workersex,datediff(year,workerborndate,getdate())
from worker
order by workerno