如何检查一年是否是闰年?
我有这段代码:
declare @year int
set @year = 1968
SELECT CASE WHEN @YEAR = <LEAPYEAR> THEN 'LEAP YEAR' ELSE 'NORMAL YEAR' END
预期结果:
LEAP YEAR
答案 0 :(得分:38)
检查2月29日:
CASE WHEN ISDATE(CAST(@YEAR AS char(4)) + '0229') = 1 THEN 'LEAP YEAR' ELSE 'NORMAL YEAR' END
或使用以下规则
CASE WHEN (@YEAR % 4 = 0 AND @YEAR % 100 <> 0) OR @YEAR % 400 = 0 THEN 'LEAP YEAR'...
答案 1 :(得分:3)
闰年计算:
(@year % 4 = 0) and (@year % 100 != 0) or (@year % 400 = 0)
如果这是真的,那么这是闰年。或者将其放在案例陈述中
select case when
(
(@year % 4 = 0) and (@year % 100 != 0) or
(@year % 400 = 0)
) then 'LEAP' else 'USUAL' end
;
答案 2 :(得分:3)
最有效的一年中的测试:
CASE WHEN @YEAR & 3 = 0 AND (@YEAR % 25 <> 0 OR @YEAR & 15 = 0) THEN ...
答案 3 :(得分:2)
这也可以帮助
DECLARE @year INT = 2012
SELECT IIF(DAY(EOMONTH(DATEFROMPARTS(@year,2,1))) = 29,1,0)
Result: 1 --(1 if Leap Year, 0 if not)
SELECT IIF(DAY(EOMONTH(DATEFROMPARTS(@year,2,1))) = 29,'Leap year','Not Leap year')
Result: Leap year
答案 4 :(得分:1)
我有更好的解决方案
CREATE FUNCTION dbo.IsLeapYear(@year INT)
RETURNS BIT AS
BEGIN
DECLARE @d DATETIME,
@ans BIT
SET @d = CONVERT(DATETIME,'31/01/'+CONVERT(VARCHAR(4),@year),103)
IF DATEPART(DAY,DATEADD(MONTH,1,@d))=29 SET @ans=1 ELSE SET @ans=0
RETURN @ans
END
GO
随意使用
答案 5 :(得分:1)
不确定将其与其他解决方案相比效率如何。但这是另一种选择。
DECLARE @year int = 2016
SELECT CASE
WHEN DATEPART(dayofyear, DATEFROMPARTS(@year, 12, 31)) = 366
THEN 'LEAP'
ELSE 'NOT LEAP'
END
答案 6 :(得分:1)
3行...但也可能是2 ...
DECLARE @Y as int = 2021;
DECLARE @Dt as char(10) = CAST(@Y as CHAR(4)) + '-02-29'
SELECT IIF(isDATE(@Dt) = 1, 1,0)
或
DECLARE @Dt as char(10) = '2020-02-29'
SELECT IIF(isDATE(@Dt) = 1, 1,0)
艾伦
答案 7 :(得分:-1)
select decode(mod(&n,4),0,'leap year' ,'not a leapyear') as CHECK_LEAPYEAR from dual
答案 8 :(得分:-1)
我疯了吗,但这不像
那样容易吗?CASE WHEN (@YEAR % 4 = 0) THEN 'LEAP YEAR' ELSE 'NORMAL YEAR' END
答案 9 :(得分:-2)
select
CASE
WHEN result = 0 THEN 'Leap_Year'
WHEN result <> 0 THEN 'Not_A_Leap_Year'
END
from(select mod((EXTRACT(YEAR FROM DATE '2013-08-23')), 4) result FROM DUAL);