Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# SQL

Vivek Vasudevan
Greenhorn
Posts: 5
Hi,

I would like to know whether there is any readymade function in MS SQL for finding out whether the year is a leap one or not. Thanks in Advance!

Vivek V
"Today is the first day of the rest of your life"

Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34084
337
Vivek,
Welcome to Javaranch!

I'm moving this to our JDBC forum, since it is about SQL and not Oracle specifically.

Ranch Hand
Posts: 2874
you can just get the year and divide it by 4. if you get the reminder it means the year is not a leap year, else it is.

i think we have a function called mod(). you can use it to in order to get the reminder.

any particular function. sorry i dont know. may be someone else.

Paul Sturrock
Bartender
Posts: 10336
Not quite. 1900, 1800, 1700 aren't Leap Years for example, though they all divide by 4. The rules are, its a Leap Year if:
• The year divides by 4, unless
• The year also divides by 100, unless
• The year divides by 400.

• Assuming you are talking about the Gregorian Calendar that is. Ugly, true, buth those are the rules. And its far easier than trying to work out when Easter is...

Can't think of any way to do it in SQL, without using functions. Easier is to do just return the date into the Java layer and work it out there (since GregorianCalendars have the isLeapYear() method).

Mani Ram
Ranch Hand
Posts: 1140
you can just get the year and divide it by 4. if you get the reminder it means the year is not a leap year, else it is.

Works fine if you are using a Julian calendar, but not with a Gregorian calendar (one which is widely used)
For example the year 1900 is divisible by 4, but is not a leap year, if you are following the Gregorian calendar.

There should be an additional check there
If the year is divisible by 100, it should also be divisible by 400. If it doesn't, then it is not a leap year