欢迎来到代码驿站!

MsSql

当前位置:首页 > 数据库 > MsSql

sql通过日期判断年龄函数的示例代码

时间:2022-07-28 11:02:00|栏目:MsSql|点击:

定义函数:

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

使用函数:

上一篇:SqlServer数据库备份与还原的实现步骤

栏    目:MsSql

下一篇:没有了

本文标题:sql通过日期判断年龄函数的示例代码

本文地址:http://www.codeinn.net/misctech/209189.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有