0

我有一个基于三列的复合主键表。

(Unit, Account, service)

我还有另外两列:(DOB这包含出生日期)& Age(这是一个新的 int 列,需要根据 DOB 进行更新,结果将是年的整数值)

我知道如何检索年龄的结果

select datediff(Year,DOB,GETDATE()) as AGE

但不确定如何根据行 DOB 数据更新整个表。

列是Unit, Account, Service, DOB, Age

4

3 回答 3

2

根据评论,坚持 Age 是不明智的,因为它每天都在变化(如果用户在不同的时区,可能更频繁)。

此外,您的 Age vs DOB 算法不准确 - 请参阅此处以获得更好的算法

因此,IMO 这是一种非持久性COMPUTED列有意义的场景,如下所示:

ALTER TABLE Person add Age 
AS DateDiff(yy,DOB,CURRENT_TIMESTAMP) 
- CASE WHEN DATEPART  (mm,DOB) <= DATEPART(mm,CURRENT_TIMESTAMP) 
       and DATEPART(dd, DOB) <= DATEPART(dd,CURRENT_TIMESTAMP)
    THEN 0 
    ELSE 1
  END
于 2012-10-26T14:32:02.333 回答
1

Get rid of the age column and calculate the age like so:

SELECT DATEDIFF(yy, DOB, getdate()) AS age FROM daffyduck

There are very rare cases that you need to store items such as age. Since age changes daily, you will have to update your records often. It is instead better to store a fixed value, such as the date of birth that can be calculated. Most DBMS's provide the functionality for doing the date arithmetic for this reason.

于 2012-10-26T14:28:12.683 回答
1

要回答您的问题:

UPDATE dob.MyTable SET Age = datediff(Year,DOB,GETDATE());

这将根据您的要求更新整个表格。

但是,我强烈建议您在这里查看所有其他答案。尤其是上面公式中的计算误差。

于 2012-10-26T14:50:33.513 回答