使用 SQL Server 从系统日期和生日计算年龄 [英] calculating age from sysdate and birthdate using SQL Server

查看:53
本文介绍了使用 SQL Server 从系统日期和生日计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何在 T-SQL 中计算年龄年、月、日

我只是想使用生日变量来计算年龄(以年为单位)

I'm simply trying to calc age (in years) using a birthdate variable

1932-04-29 00:00:00.000

和 SYSDATETIME( ) 在 SQL Server 中,其中由

and SYSDATETIME( ) in SQL Server, where by

SELECT year(Sysdatetime() - Birthdate) as Age

生产(出人意料地):1980

produces (surprisingly) : 1980

我错过了什么?我预计会得到 80!

What did I miss? I expected to get 80!

推荐答案

计算年龄并不像乍看起来那么简单.

Calculating age is not as simple as it might first appear.

如果您使用 Datediff,您会得到绝对年份的差异,而不是年龄.

If you use Datediff you get a difference in absolute years, which is not the age.

例如

select DATEDIFF(yy, '1980-12-31', getdate())

将返回 32,而相关人员的年龄是 31.

will return 32, whereas the age of the person in question is 31.

这可能足以满足您的目的.更准确,但还是错误,可以使用

This might be accurate enough for your purposes. More accurate, but still wrong, you can use

select convert(int,DATEDIFF(d, '1933-10-31', getdate())/365.25)

这在大多数时间是正确的.

或者你可以写一个更复杂的函数....

Or you can write a more complex function....

这篇关于使用 SQL Server 从系统日期和生日计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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