如何将UDF与select语句一起使用?

时间:2015-09-29 04:26:51

标签: sql-server user-defined-functions

我创建了一个标量用户定义函数,该函数将接受一个出生日期并返回一个人将在15年后的年龄。

CREATE FUNCTION AgeIn15 (@DateOfBirth DATE)
RETURNS INT
AS
BEGIN
    RETURN Convert(INT, DateAdd(year, 15, DateDiff(year, @DateOfBirth, GetDate())))
END

现在我想使用创建的UDF来显示我的表marketing_list中所有人的年龄以及他们的原始信息。我该怎么做呢?我试过了,但是我收到了一个错误

SELECT *
FROM marketing_list AgeIn15(marketing_list.DateOfBirth)

SELECT *
    ,AgeIn15(marketing_list.Date_of_Birth)
FROM marketing_list
WHERE AgeIn15(Date_of_Birth) > 45

2 个答案:

答案 0 :(得分:0)

添加架构名称:

SELECT *, dbo.AgeIn15(m.Date_of_Birth) AS col_name
FROM marketing_list AS m;

SELECT *
    ,dbo.AgeIn15(m.Date_of_Birth) AS col_name
FROM marketing_list m
WHERE dbo.AgeIn15(m.Date_of_Birth) > 45

您可以选择使用CROSS APPLY

Select *
from marketing_list AS m
CROSS APPLY (SELECT dbo.AgeIn15(m.Date_of_Birth)) AS c(col_name)

<强> Demo

SELECT  *, dbo.AgeIn15(t.c) AS col_name
FROM (SELECT '2000-01-01') AS t(c);

SELECT  *
FROM (SELECT '2000-01-01') AS t(c)
CROSS APPLY (SELECT dbo.AgeIn15(t.c)) AS c(col_name)

您的功能应如下所示:

CREATE FUNCTION dbo.AgeIn15 (@DateOfBirth DATE)
RETURNS INTEGER
AS
BEGIN
    RETURN DATEDIFF(year,@DateOfBirth,GETDATE()) + 15
END

你做了什么没有任何意义:

Convert(integer,DateAdd(year,15,DateDiff(year,@DateOfBirth,GetDate())))
  1. 计算DATEDIFF - 它返回数年确定
  2. DATEADD(year, 15, number) - 返回日期15年+ 1900-01-number 失败
  3. CONVERT(INTEGER, DATE) - 它会返回从1900-01-01开始的天数失败

答案 1 :(得分:0)

CREATE FUNCTION AgeIn15 (@DateOfBirth DATE)
RETURNS INT
AS
BEGIN
    RETURN 
       -- get the year today + 15 years
       (
          (DATEPART(YEAR, GETDATE() ) + 15) - 
          -- minus the year of date of birth
          DATEPART(YEAR,@DateOfBirth)
       )
       -- its like saying (2015 + 15)-09-29 - (1990)-09-19 = 40
END

SELECT *
    , dbo.AgeIn15(mlist.Date_of_Birth) AS [AgeAfterFifteenYears]
FROM marketing_list AS mlist

希望这有助于