SELECT或exec结果

时间:2013-10-13 19:45:21

标签: sql sql-server

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

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

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

这是你要找的吗?

DECLARE @dob date;
SET @dob = '1980-01-01';
SELECT udfCalculateAge(@dob, NULL);

答案 2 :(得分:1)

SELECT [dbo].[udfCalculateAge]( @dateBirth,default )

SELECT [dbo].[udfCalculateAge]( @dateBirth,@endDate )