您现在的位置是:网站首页> 编程资料编程资料
sql通过日期判断年龄函数的示例代码_MsSql_
2023-05-26
345人已围观
简介 sql通过日期判断年龄函数的示例代码_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
使用函数:

到此这篇关于sql通过日期判断年龄函数的示例代码的文章就介绍到这了,更多相关sql日期计算年龄内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- 利用 SQL Server 过滤索引提高查询语句的性能分析_MsSql_
- SqlServer数据库远程连接案例教程_MsSql_
- Spark SQL的整体实现逻辑解析_MsSql_
- 数据库之SQL技巧整理案例_MsSql_
- SQL SERVER提交事务回滚机制_MsSql_
- SQL Server中使用判断语句(IF ELSE/CASE WHEN )案例_MsSql_
- SQL Server代理:理解SQL代理错误日志处理方法_MsSql_
- SQL Server作业失败:无法确定所有者是否有服务器访问权限的解决方法_MsSql_
- SQLServer 错误: 15404,无法获取有关 Windows NT 组/用户 WIN-8IVSNAQS8T7\Administrator 的信息_MsSql_
- SQL 尚未定义空闲 CPU 条件 - OnIdle 作业计划将不起任何作用_MsSql_
