根据SQL Server的出生日期检查年龄

发布于 2025-02-10 09:34:48 字数 600 浏览 0 评论 0 原文

我试图检查从出生之日起用户的年龄,以确保年龄在16至80之间,当数据插入表中时,

出生日期是

我疲倦的日期数据类型,寻找多个解决方案,而无需他们在插入数据时检查它,

我找到了此帮助文章以获取当前日期: https://learnsql.com/cookbook/how-to-to-get-the-current-date-without-without time-in-t-sql/#:~: text = text = toxt = time; %20元%20DATE%20 and%20Time%20IN%20平方%20Server,20%2010%%3A22%3A34%20

I am trying to check the Age of a user from the Date Of Birth to make sure Age is between 16 and 80, When the data is inserted into the table

The Date of Birth is a DATE datatype

I have tired looked for multiple solutions and none of them check it when the data is inserted

I have found this help out article to get the current Date with only the Date: https://learnsql.com/cookbook/how-to-get-the-current-date-without-time-in-t-sql/#:~:text=To%20get%20the%20current%20date%20and%20time%20in%20SQL%20Server,20%2010%3A22%3A34%20.

But i can't seem to get it to work with the CHECK function when creating the table

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

筱武穆 2025-02-17 09:34:48

另一个答案无法正确处理部分年。

>作为 20060627 ,基于日期> 的计算将返回 true 。这是因为日期仅计算两个日期之间通过的日期边界

另一个问题是它不能使用索引。

更正确的caluclation使用 dateadd 在当前日期:

WHERE DateOfBirth <= DATEADD(year, -16, CAST(GETDATE() AS date))
  AND DateOfBirth >  DATEADD(year, -80, CAST(GETDATE() AS date));

您还需要作为日期施放否则最终会遇到转换问题

The other answer does not correctly deal with partial years.

For example, given GETDATE() as 20220626 and a DateOfBirth as 20060627, a calculation based on DATEDIFF will return TRUE. This is because DATEDIFF just counts the number of date boundaries that pass between the two dates.

Another issue is that it cannot use indexes.

A more correct caluclation uses DATEADD against the current date:

WHERE DateOfBirth <= DATEADD(year, -16, CAST(GETDATE() AS date))
  AND DateOfBirth >  DATEADD(year, -80, CAST(GETDATE() AS date));

You also need CAST AS date otherwise you end up with conversion issues

db<>fiddle

贪恋 2025-02-17 09:34:48

类似:

DATEDIFF(year, DateOfBirth, GETDATE()) BETWEEN 16 AND 80

不是最终代码,但可以希望在您的方案中插入:)

Something like:

DATEDIFF(year, DateOfBirth, GETDATE()) BETWEEN 16 AND 80

Not final code, but could be inserted in your scenario hopefully :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文