SQL Server功能失败,逻辑似乎很好

时间:2014-10-21 15:37:00

标签: sql-server tsql

无论输入什么,此SQL函数都返回0,我在哪里搞砸了? 我们的想法是返回一个字符串或日期,表示2月的最后一天,以四位数年份作为输入

CREATE FUNCTION [dbo].[LastDayOfFeb] 
----------------------------------------------------------------------------------
 --This returns the last day of February by figuring out when leap year occurs
 
--Leap years are those years that are evenly divisible by 4, except for  
--centennial years (those ending in -00), which receive the extra  
--day only if they are evenly divisible by 400 
-- Input SMALLINT , Output DATE
----------------------------------------------------------------------------------
 (@Year SMALLINT) 
returns VARCHAR

AS 
  BEGIN 
  set @year = cast(@year as smallint)
      --1. ______________Not a multiple of 4 -------------------------> NO 
      IF @Year % 4 <> 0 
        RETURN '0228' + Cast(@YEAR AS VARCHAR) 

      --2. ______________A multiple of 4 but NOT Centennial ----------> YES 
      IF @Year % 4 <> 0 
        RETURN '0229' + Cast(@YEAR AS VARCHAR)

      --3. ______________A Centennial and a multiple of 400 ----------> YES 
      IF @Year % 400 = 0 
        RETURN '0229' + Cast(@YEAR AS VARCHAR)

      --4. ______________A Centennial but NOT a multiple of 400 ------> NO 
      RETURN '0228' + Cast(@YEAR AS VARCHAR)
  END  
GO

2 个答案:

答案 0 :(得分:4)

尝试将RETURN VARCHAR替换为RETURN VARCHAR(10)。通过不指定返回字符串的大小,它假设长度为1,这就是为什么你只得到前导&#39; 0&#39;。

答案 1 :(得分:0)

declare @year int = 2005
declare @date = dateadd(year, @year - 1900, '19000101')

select @date = dateadd(month, 2, @date)
select @date = dateadd(day, -1, @date)
select @date

而不是使用字符串。

作为一个函数,这将是

CREATE FUNCTION [dbo].[LastDayOfFeb]
  (@year SMALLINT)
RETURNS DATE
AS
BEGIN    
    RETURN dateadd(day, -1,
                   dateadd(month, 2, 
                           dateadd(year, @year - 1900, 0)))

END

使用/测试的一个例子

WITH cte AS (
  SELECT year = 2000, last_day_of_feb = dbo.LastDayOfFeb(2000)
  UNION ALL
  SELECT year + 1, dbo.LastDayOfFeb(year + 1)
  FROM cte
  WHERE year + 1 <= 2040
)

SELECT *
FROM cte

SQL Fiddle