使用SQL Server 2005中的sql查询从当前日期的出生日期开始查找年龄?

时间:2010-11-18 06:18:05

标签: sql sql-server-2005

使用sql查询从当前日期的出生日期开始查找年龄?

3 个答案:

答案 0 :(得分:1)

你可能想要参考史蒂夫·卡斯(Steve Kass)开发的well known solution,其中包括许多边缘案例,包括闰年。这里仅供参考:

DECLARE @birthdate SMALLDATETIME, @endDate SMALLDATETIME 
SET @birthdate = '19791204' 
SET @endDate = GETDATE() 

SELECT DATEDIFF 
( 
    YEAR, 
    @birthdate, 
    @endDate 
) - CASE 
    WHEN 100 * MONTH(@endDate) + DAY(@endDate) 
    < 100 * MONTH(@birthdate) + DAY(@birthdate) 
    THEN 1 ELSE 0 END 

答案 1 :(得分:0)

Drop table Bird;

CREATE TABLE Bird (
    name VARCHAR(20), 
    owner VARCHAR(20),
    species VARCHAR(20), 
    sex CHAR(1), 
    birth DATE, 
    death DATE
);



INSERT INTO  Bird VALUES ('BlueBird','Joe','Car','f','1999-03-30',NULL);
INSERT INTO  Bird VALUES ('RedBird','Yin','Bus','m','1979-04-30',NULL);
INSERT INTO  Bird VALUES ('RedBird','Yin','Bus','m','1998-01-30',NULL);



SELECT name, birth, CURDATE(),
       (YEAR(CURDATE())-YEAR(birth))
        - (RIGHT(CURDATE(),5)<RIGHT(birth,5))
       AS age
       FROM Bird;

答案 2 :(得分:0)

DECLARE
@dob DATETIME
BEGIN
SET @dob = '19791204' -- set your birthday in datetime..
SELECT DATEDIFF(YEAR,@dob,GETDATE()) AS AGE
-- if you do it reverse :  DATEDIFF(YEAR,GETDATE(),@dob,) you will get negative
-- refer : http://msdn.microsoft.com/en-us/library/ms189794.aspx
END