温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

sql实现通过日期判断年龄函数

发布时间:2021-07-16 11:55:43 来源:亿速云 阅读:306 作者:chen 栏目:开发技术

这篇文章主要介绍“sql实现通过日期判断年龄函数”,在日常操作中,相信很多人在sql实现通过日期判断年龄函数问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”sql实现通过日期判断年龄函数”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

定义函数:

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实现通过日期判断年龄函数”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

sql
AI