使用 SQL Server 从系统日期和生日计算年龄

编程入门 行业动态 更新时间:2024-10-27 10:33:41
本文介绍了使用 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 从系统日期和生日计算年龄

本文发布于:2023-10-18 11:46:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504144.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:年龄   日期   生日   系统   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!