sql通过日期判断年龄函数的示例代码
定义函数:
CREATE FUNCTION [dbo].[GetAge](@BirthDay nvarchar(20) --生日)RETURNS varchar(20)ASBEGINif(@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) elsebeginset @months = @months - 1if 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) = 2if (year(@birthday)%4 = 0 and year(@birthday)%100 <> 0) or year(@birthday)%400 = 0set @days = 29-day(@birthday)+day(GETDATE())elseset @days = 28-day(@birthday)+day(GETDATE())end if @months < 0beginset @years = @years - 1set @months = @months + 12end if @years = 0 and @months = 0 beginreturn convert(varchar,@days+1) + '天'end if @years > 0set @age = cast(@years as varchar(5)) + '岁' if @years < 3 and @months > 0 and @years>-1 beginset @age = @age + cast(@months as varchar(5)) + '月' end if @years<0 set @age='' RETURN @ageEND
【sql通过日期判断年龄函数的示例代码】使用函数:
文章图片
到此这篇关于sql通过日期判断年龄函数的示例代码的文章就介绍到这了,更多相关sql日期计算年龄内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- gitlab|gitlab 通过备份还原 admin/runner 500 Internal Server Error
- py连接mysql
- 2019-01-18Mysql中主机名的问题
- MySql数据库备份与恢复
- whlie循环和for循环的应用
- mysql|InnoDB数据页结构
- 数据库|SQL行转列方式优化查询性能实践
- mysql中视图事务索引与权限管理
- MYSQL主从同步的实现
- 0811~2017下个旅程~利川