如何在SQL Server查询中基于DateOfBirth列更新Age列

时间:2015-10-13 07:51:09

标签: sql-server

我需要编写一个SQL查询来更新Age列中的DateOfBirth列。下面是一个包含一些现成数据的示例表。

CREATE TABLE Students
(
    ID INT IDENTITY,
    Name VARCHAR (100),
    DateOfBirth date,
    Age INT,
    ClassID INT,
    SectionID INT,
    PRIMARY KEY (ID)
)

INSERT INTO Students (Name, DateOfBirth, Age, ClassID, SectionID) 
VALUES ('Adam','2003-06-16', 0, 6, 2)

INSERT INTO Students (Name, DateOfBirth, Age, ClassID, SectionID) 
VALUES ('Botham','2001-03-22', 0, 8, 1)

INSERT INTO Students (Name, DateOfBirth, Age, ClassID, SectionID) 
VALUES ('Hillton',Null, 0, 7, 2)

INSERT INTO Students (Name, DateOfBirth, Age, ClassID, SectionID) 
VALUES ('Rasty','2004-12-02', 0, 5, 1)

INSERT INTO Students (Name, DateOfBirth, Age, ClassID, SectionID) 
VALUES ('Holistar',Null, 0, 8, 1)

3 个答案:

答案 0 :(得分:0)

虽然我不同意你的表,但是你想要的是:

update Students
set Age = DATEDIFF(yy, DateOfBirth, GETDATE()) - CASE WHEN (MONTH(DateOfBirth) > MONTH(GETDATE())) OR (MONTH(DateOfBirth) = MONTH(GETDATE()) AND DAY(DateOfBirth) > DAY(GETDATE())) THEN 1 ELSE 0 END

答案 1 :(得分:0)

不需要列,而是需要不断更新。我去了计算专栏,我使用了这个问题中的公式:How to calculate age (in years) based on Date of Birth and getDate()

CREATE TABLE Students
(
    ID INT IDENTITY
    , Name VARCHAR(100)
    , DateOfBirth DATE
    , Age AS CONVERT(INT, ROUND(DATEDIFF(HOUR, DateOfBirth, GETDATE()) / 8766.0, 0))
    , ClassID INT
    , SectionID INT
    , PRIMARY KEY (ID)
);

有了这个,您的年龄列应该始终是最新的。

答案 2 :(得分:-1)

我希望这可以帮助您找到解决方案

SELECT Name,Age = DATEDIFF(day,DateOfBirth,GETDATE()),
[YEARS]  = DATEDIFF(day,DateOfBirth,GETDATE()) / 365,
[MONTHS] = (DATEDIFF(day,DateOfBirth,GETDATE()) % 365) / 30,
[DAYS]   = (DATEDIFF(day,DateOfBirth,GETDATE()) % 365) % 30
FROM Students

您的Age列为INTEGER,因此您可以使用它,这将在年内为您提供Age

UPDATE Students SET Age = DATEDIFF(day,DateOfBirth,GETDATE()) / 365

如果您得到更准确的答案,那么您可以使用

UPDATE Students SET Age = FLOOR(DATEDIFF(day, DateOfBirth, GETDATE()) / 365.242)

Reference将帮助您计算闰年