站长网 MsSql教程 数据库中通过日期计算年龄的SQL语句

数据库中通过日期计算年龄的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语句是什么”就介绍到这了,如果大家觉得不错可以参考了解看看,如果想要了解更多,小编每天都会为大家更新不同的知识。

本文来自网络,不代表站长网立场,转载请注明出处:https://www.tzzz.com.cn/html/jc/mssql/2024/0605/45961.html

作者: dawei

【声明】:站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。
联系我们

联系我们

0577-28828765

在线咨询: QQ交谈

邮箱: xwei067@foxmail.com

工作时间:周一至周五,9:00-17:30,节假日休息

返回顶部