zoukankan      html  css  js  c++  java
  • 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  

    使用函数:

     注:此函数只是 3 岁以下才显示月,可根据需求自定义修改

  • 相关阅读:
    Jzoj3756 【NOI2014】动物园
    Bzoj5088 HDU 6000 Wash
    Bzoj5088 HDU 6000 Wash
    Jzoj3486 道路改建
    Jzoj3486 道路改建
    合作网络
    工人的请愿书
    划分成回文串
    单向TSP
    旅行
  • 原文地址:https://www.cnblogs.com/Allofus/p/15016007.html
Copyright © 2011-2022 走看看