MSSQL 计算年龄函数
/* 计算年龄函数 */ CREATE FUNCTION DBO.GETAGE ( @BIRTHDAY DATETIME, @NOWDAY DATETIME ) RETURNS INT AS BEGIN DECLARE @AGE INT, @YEAR INT, @MONTH INT, @DAY INT SET @AGE = 0 SET @YEAR = 0 SET @MONTH = 0 SET @DAY = 0 SET @YEAR = DATEPART(YEAR,@NOWDAY) - DATEPART(YEAR, @BIRTHDAY) SET @MONTH = DATEPART(MONTH,@NOWDAY) - DATEPART(MONTH, @BIRTHDAY) SET @DAY = DATEPART(DAY,@NOWDAY) - DATEPART(DAY, @BIRTHDAY) IF( @MONTH > 0) SET @AGE = @YEAR IF( @MONTH < 0) SET @AGE = @YEAR - 1 IF(@MONTH = 0) BEGIN IF( @DAY >= 0) SET @AGE = @YEAR ELSE SET @AGE = @YEAR -1 END RETURN(@AGE) END
最近找到另一种更好的方法:
SELECT FLOOR(DATEDIFF(DAY,@BRITHDAY,GETDATE())/365.25)