0

我有一个日期函数返回今天的日期减去出生日期。如何选择或执行结果?

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
4

3 回答 3

2

你可以简单地在选择中返回它

DECLARE @dob AS DATE = '19800101'
DECLARE @enddate AS DATE = '20200101'

SELECT [dbo].[udfCalculateAge](@dob, @enddate)

您也可以在从表中选择时使用它来返回函数的值以及其他列:

SELECT dob, enddate, [dbo].[udfCalculateAge](dob, enddate)
FROM table1

您也可以在其他子句中使用它,例如WHERE,但出于性能原因不建议这样做。

如果您想使用带有默认参数的函数,请使用default作为第二个参数,因为您仍然需要指定所有参数:

SELECT [dbo].[udfCalculateAge](@dob, default)
于 2013-10-13T19:49:50.503 回答
1

这是你要找的吗?

DECLARE @dob date;
SET @dob = '1980-01-01';
SELECT udfCalculateAge(@dob, NULL);
于 2013-10-13T19:50:00.423 回答
1
SELECT [dbo].[udfCalculateAge]( @dateBirth,default )

或者

SELECT [dbo].[udfCalculateAge]( @dateBirth,@endDate )
于 2013-10-13T19:52:10.690 回答