如何在简单更新中设置一个年龄

发布于 2025-02-09 16:57:52 字数 247 浏览 2 评论 0原文

我有一个桌子,上面有两个行“生日”和“年龄”。实际上,“年龄”是空的。

我该如何从生日开始简单更新我的年龄?

create table ex(
  birthday nvarchar(50),
  age int
)

insert into ex values ('02-04-1962',null)


select * from ex


--update ex set age = ....

I have a table with two rows "birthday" and "age". Actually the row "age" is empty.

How can I with a simple update set my age from the birthday ?

create table ex(
  birthday nvarchar(50),
  age int
)

insert into ex values ('02-04-1962',null)


select * from ex


--update ex set age = ....

DB FIDDLE

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

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

发布评论

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

评论(1

美人迟暮 2025-02-16 16:57:52

我认为您需要由于某种原因计算年龄,但是存储可以计算的数据不是一个好主意,尤其是在此数据会随着时间的流逝(例如您的情况)过期的情况下。

撇开这是一种方法:

您将需要从字符串到日期将生日转换为日期,然后使用dedediff

update ex set age = datediff(year, cast(birthday as date), getdate())

I assume you need to calculate age for some reason, but it is not a good idea to store data that can be calculated, especially if this data will be expired over time, such as in your case.

Putting that aside, this is one way of doing that:

You will need to convert birthday from string to date, then use datediff

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