主页 > 知识库 > sql通过日期判断年龄函数的示例代码

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

热门标签:铁路电话系统 AI电销 呼叫中心市场需求 Linux服务器 地方门户网站 百度竞价排名 服务外包 网站排名优化

定义函数:

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 @years0  
 set @age=''  
 RETURN @age  
END

使用函数:

到此这篇关于sql通过日期判断年龄函数的示例代码的文章就介绍到这了,更多相关sql日期计算年龄内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
  • Postgresql 通过出生日期获取年龄的操作
  • Mysql出生日期转换为年龄并分组统计人数的方法示例
  • Mysql中通过生日计算年龄的多种方法

标签:仙桃 湘潭 兰州 黄山 铜川 崇左 衡水 湖南

巨人网络通讯声明:本文标题《sql通过日期判断年龄函数的示例代码》,本文关键词  ;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 收缩
    • 微信客服
    • 微信二维码
    • 电话咨询

    • 400-1100-266