我有一个日期函数返回今天的日期减去出生日期。如何选择或执行结果?
CREATE FUNCTION [dbo].[udfCalculateAge]
(
@DOB AS DATE,
@EndDate as DATE = '2999-01-01' -- Defaul is today's date (see below) but any date can be used here
)
RETURNS TINYINT
AS
BEGIN
DECLARE @Result as TINYINT
-- IF DEFAULT VALUE (marked as 2999-01-01 as it doesn't accept functions) IS USED THEN USE TODAY'S DATE
IF @EndDate = '2999-01-0'
SET @EndDate = GETDATE()
IF @DOB >= @EndDate -- trap errors
SET @Result = 0
ELSE
BEGIN
-- check if the person had its birthday in the specified year and calculate age
IF (MONTH(@EndDate)*100)+DAY(@EndDate) >= (MONTH(@DOB)*100)+DAY(@DOB)
SET @Result = DATEDIFF(Year,@DOB,@EndDate)
ELSE
SET @Result = DATEDIFF(Year,@DOB,@EndDate)-1
END
RETURN @Result
END