if ((year modulo 4 is 0) and (year modulo 100 is not 0)) orI've been using this algorithm all my programming life, and there's really nothing wrong with it. SQL Server, however, can accurately handle date data and have a couple functions that can be used to check for leap year without passing through this complicated algorithm. What I did is just to check if the expression is a valid date expression using the ISDATE() function.
(year modulo 400 is 0) then
leap
else
not_leap
Running the queries below:
select isdate('20070229') as validdatewill return the following result sets:
select isdate('20080229') as validdate
validdateSo if I have an integer year variable, I just need to build the date string.
-----------
0
validdate
-----------
1
set nocount onHere are the result sets:
declare @YearVar int
set @YearVar = 2007
select
isdate(cast(@YearVar as varchar(4)) + '0229') as validdate
set @YearVar = 2008
select
isdate(cast(@YearVar as varchar(4)) + '0229') as validdate
validdateTo ensure that the date string will be properly interpreted, I use the unseparated date string format. For more on that, read my old notes.
-----------
0
validdate
-----------
1
Here's a sample code that illustrate how this algorithm works:
set nocount on
declare @YearVar int
set @YearVar = 2007
select
@YearVar as YearVar,
case
when isdate(cast(@YearVar as varchar(4)) + '0229') = 1 then
'leap year'
else 'not leap year'
end as validdate
YearVar validdate
----------- -------------
2007 not leap year
set @YearVar = 2008
select
@YearVar as YearVar,
case
when isdate(cast(@YearVar as varchar(4)) + '0229') = 1 then
'leap year'
else 'not leap year'
end as validdate
YearVar validdate
----------- -------------
2008 leap year
~~CK
No comments:
Post a Comment