如何在 T-SQL 中用年、月和日计算年龄 [英] How to calculate age in T-SQL with years, months, and days

查看:33
本文介绍了如何在 T-SQL 中用年、月和日计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 T-SQL (SQL Server 2000) 中计算某人年龄的最佳方法是什么?

What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)?

datediff 函数不能很好地处理年份边界,而且将月份和日期分开会很麻烦.我知道我可以在客户端相对容易地做到这一点,但我想在我的 stored程序.

The datediff function doesn't handle year boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my stored procedure.

推荐答案

这里有一些 T-SQL,它为您提供自 @date 中指定的日期以来的年数、月数和天数.它考虑到 DATEDIFF() 计算差异而不考虑它是哪一个月或哪一天(所以 8/31 和 9/1 之间的月份差异是 1 个月)并使用 case 语句处理它,该语句减少结果,其中合适.

Here is some T-SQL that gives you the number of years, months, and days since the day specified in @date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate.

DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int
SELECT @date = '2/29/04'

SELECT @tmpdate = @date

SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(m, @months, @tmpdate)
SELECT @days = DATEDIFF(d, @tmpdate, GETDATE())

SELECT @years, @months, @days

这篇关于如何在 T-SQL 中用年、月和日计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆