sql通过日期判断年龄函数的示例代码
程序员文章站
2022-03-22 17:04:50
定义函数:create function [dbo].[getage] ( @birthday nvarchar(20) --生日 ) returns varchar(20) as beg...
定义函数:
create function [dbo].[getage] ( @birthday nvarchar(20) --生日 ) returns varchar(20) as begin if(@birthday is null or @birthday='') return ''; -- declare the return variable here declare @age varchar(20) declare @years int declare @months int declare @days int -- add the t-sql statements to compute the return value here set @age = '' set @years = year(getdate()) - year(@birthday) set @months = month(getdate()) - month(@birthday) if day(@birthday)<=day(getdate()) set @days = day(getdate()) - day(@birthday) else begin set @months = @months - 1 if month(@birthday) in (1,3,5,7,8,10,12) set @days = 31-day(@birthday)+day(getdate()) else if month(@birthday) in (4,6,9,11) set @days = 30-day(@birthday)+day(getdate()) else if month(@birthday) = 2 if (year(@birthday)%4 = 0 and year(@birthday)%100 <> 0) or year(@birthday)%400 = 0 set @days = 29-day(@birthday)+day(getdate()) else set @days = 28-day(@birthday)+day(getdate()) end if @months < 0 begin set @years = @years - 1 set @months = @months + 12 end if @years = 0 and @months = 0 begin return convert(varchar,@days+1) + '天' end if @years > 0 set @age = cast(@years as varchar(5)) + '岁' if @years < 3 and @months > 0 and @years>-1 begin set @age = @age + cast(@months as varchar(5)) + '月' end if @years<0 set @age='' return @age end
使用函数:
到此这篇关于sql通过日期判断年龄函数的示例代码的文章就介绍到这了,更多相关sql日期计算年龄内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 私域运营不好,90%的人忽略了这一点