简体   繁体   English

将 DATEDIFF 与 ALTER TABLE 一起使用的问题

[英]Issues using DATEDIFF with ALTER TABLE

I'm trying to add a computed column into an existing database table that will calculate age eg "23" from field "DOB" stored as YEAR (4) eg 1988.我正在尝试将一个计算列添加到现有数据库表中,该表将计算年龄,例如从存储为 YEAR (4) 的字段“DOB”(例如 1988)中的“23”。

Using the below, I get a使用下面的,我得到一个

1582 error - an incorrect parameter count in the call to native function 'DATEDIFF'. 1582 错误 - 调用本机 function 'DATEDIFF' 时参数计数不正确。

ALTER TABLE names ADD Age INT GENERATED ALWAYS AS (DATEDIFF('year', DOB, CURDATE))

Many examples I've found online have similar layout in terms of parameter count (some use GETDATE or NOW instead of CURDATE).我在网上找到的许多示例在参数计数方面都有相似的布局(有些使用 GETDATE 或 NOW 而不是 CURDATE)。

Anyone have any idea what I'm doing wrong?任何人都知道我做错了什么?

Thanks to RigsFolly & Barmar for the feedback.感谢 RigsFolly & Barmar 的反馈。 I made a fresh cup of tea and looked at it again.我泡了一杯新茶,又看了一遍。

With DATEDIFF, it seems the MYSQL Server syntax can use the datepart and then use two dates to calculate (including GETDATE).有了DATEDIFF,好像MYSQL Server语法可以使用datepart,然后用两个日期来计算(包括GETDATE)。 I'm using MySQL through myphp admin which doesnt seem to like the datepart.我通过 myphp 管理员使用 MySQL,它似乎不喜欢日期部分。

I dropped the datepart and changed the date format of the stored DOB field from "YEAR" to "DATE".我删除了日期部分并将存储的 DOB 字段的日期格式从“YEAR”更改为“DATE”。 As a result I no longer received the parameter error and by default the output of the DATEDIFF was returned in days.结果我不再收到参数错误,默认情况下 DATEDIFF 的 output 以天为单位返回。 I then divided the output by 365 to get years.然后我将 output 除以 365 得到年数。

My original order was wrong too which gave me the DATEDIFF output as a negative value, so changed the order and it works a charm.我原来的顺序也是错误的,这给了我 DATEDIFF output 作为负值,所以改变了顺序并且它很有魅力。 Thank you.谢谢你。

ALTER TABLE names ADD Age INT GENERATED ALWAYS AS (DATEDIFF(CURDATE(), DOB) / 365);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM