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

作者:kueizheng 时间:2024-01-13 21:01:02 

定义函数:


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.cnblogs.com/Allofus/p/15016007.html

标签:sql,日期,年龄
0
投稿

猜你喜欢

  • SQL Server与Oracle、DB2的优劣对比

    2009-01-07 14:16:00
  • 用Python实现协同过滤的教程

    2023-08-30 12:28:55
  • 解读数据库的嵌套查询的性能问题

    2024-01-20 17:00:06
  • 用python3读取python2的pickle数据方式

    2023-06-05 09:45:48
  • Python设计密码强度校验程序

    2022-09-29 08:37:12
  • 使用python+pandas读写xlsx格式中的数据

    2023-03-25 00:55:16
  • Pandas的read_csv函数参数分析详解

    2021-06-02 13:40:15
  • Python 中如何使用 virtualenv 管理虚拟环境

    2022-02-20 00:57:44
  • Python实现爬取网页中动态加载的数据

    2021-08-11 18:35:27
  • python中有关时间日期格式转换问题

    2023-03-17 07:43:12
  • python统计字母、空格、数字等字符个数的实例

    2022-10-04 12:02:29
  • php如何利用ffmpeg获取视频第一帧为缩略图

    2024-05-03 15:48:20
  • Mootools 1.2教程(12)——用Drag.Move实现拖拽和拖放

    2008-12-05 12:29:00
  • python GUI库图形界面开发之PyQt5时间控件QTimer详细使用方法与实例

    2021-01-04 21:56:00
  • 实例讲解Python中SocketServer模块处理网络请求的用法

    2021-04-16 13:25:27
  • 浅谈pandas中shift和diff函数关系

    2022-11-15 08:48:42
  • mysql sock 文件解析及作用讲解

    2024-01-26 13:15:47
  • python一行输入n个数据问题

    2023-09-11 21:50:48
  • 详解SQL Server中数据库快照工作原理

    2009-01-21 14:18:00
  • Pycharm中出现ImportError:DLL load failed:找不到指定模块的解决方法

    2021-09-04 06:14:32
  • asp之家 网络编程 m.aspxhome.com