MS SQL 2012函数不返回任何值

时间:2016-04-12 16:50:52

标签: sql-server sql-server-2012

我可能遗漏了一些明显但我无法找到为什么以下函数在使用例如SELECT * FROM dbo.Age('2016-03-01','2016-03-31')。它应该以年月数格式返回年龄。

    CREATE FUNCTION [dbo].[Age] (@DateFrom DATETIME, @DateTo DATETIME)
RETURNS @Staz TABLE (Years INT, Months INT, Days INT)

AS
BEGIN
DECLARE @Years int, @Months int, @Days int
IF DAY(@DateFrom)=1 and MONTH(@DateFrom)=1 and DAY(@DateTo)=31 and MONTH(@DateTo)=12
 BEGIN
  IF YEAR(@DateFrom)=YEAR(@DateTo)
   SET @Years = @Years + 1
  ELSE
   SET @Years = @Years + (YEAR(@DateTo) - YEAR(@DateFrom) + 1)
 END
ELSE
 BEGIN
  IF MONTH(@DateFrom)=MONTH(@DateTo) and YEAR(@DateFrom)=YEAR(@DateTo)
   BEGIN
    IF DAY(@DateFrom)=1 and DAY(DATEADD(day,1,@DateTo))= 1
     SET @Months = @Months + 1
    ELSE
     BEGIN
      SET @Days =  @Days + Day(@DateTo) - Day(@DateFrom) + 1
     END
   END
  ELSE
  BEGIN
   IF  YEAR(@DateFrom)=YEAR(@DateTo)
    BEGIN
     SET @Months = @Months + (MONTH(@DateTo) - MONTH(@DateFrom) - 1)
    END
   ELSE
    BEGIN
     SET @Years = @Years + (YEAR(@DateTo) - YEAR(@DateFrom) - 1)
     SET @Months = @Months + (12 - Month(@DateFrom) + Month(@DateTo) -1)
                END
    IF DAY(@DateFrom)= 1
     SET @Months = @Months + 1
    ELSE
    IF DAY(@DateFrom)>1
     BEGIN
     DECLARE @TempData datetime
     SET @TempData = DATEADD(month,1,DATEADD(day,1-DAY(@DateFrom),@DateFrom))
     SET @Days = @Days + DATEDIFF(day,@DateFrom,@TempData)
     END
    IF DAY(DATEADD(day,1,@DateTo))<>1
     SET @Days = @Days + DAY(@DateTo)
      IF DAY(DATEADD(day,1,@DateTo))=1
     SET @Months = @Months+1
  END
 END

SET @Months = @Months + @Days/30
SET @Days = @Days%30
SET @Years = @Years + @Months/12
SET @Months = @Months%12

RETURN
END

1 个答案:

答案 0 :(得分:2)

您似乎没有在函数

中的任何位置插入@Staz表

在表格的末尾添加一个带有适当值的插入,你应该让你的表格返回值