0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【MySQL】うるう年を判定するストアドファンクション

Last updated at Posted at 2020-03-08

はじめに

以前は業務でMySQLを使うことが多かったですが、最近はご無沙汰しているので、ちょっとしたリハビリにMySQLのストアドファンクションを作ってみました。

専用のテーブルを用意するのはちょっと面倒だったので、今回はテーブルが不要で作れる「うるう年の判定処理」を題材にしてみました。

作成したSQL

  • 引数には、うるう年であるかを判定したい西暦年(4桁)を指定します。
  • 戻り値は、引数の西暦年がうるう年であれば1、うるう年でない場合は0を返します。
うるう年を求めるストアドファンクション
DELIMITER //

/*
 うるう年であるかを判定する関数。
 year:4桁の西暦年
 return:うるう年であれば1、それ以外の年は0を返す。
 */
CREATE FUNCTION is_leap_year(year INT) RETURNS BOOLEAN DETERMINISTIC
BEGIN
  DECLARE result TINYINT;
  set result = 0;
  
  IF MOD(year, 4)=0 AND MOD(year, 100)<>0 THEN
    SET result=1;
  ELSEIF MOD(year, 400)=0 THEN
    SET result=1;
  END IF;
  
  RETURN(result);
END;
//

DELIMITER ;

実行結果

実行結果
mysql> select is_leap_year(2019);
+--------------------+
| is_leap_year(2019) |
+--------------------+
|                  0 |
+--------------------+
1 row in set (0.00 sec)

mysql> select is_leap_year(2020);
+--------------------+
| is_leap_year(2020) |
+--------------------+
|                  1 |
+--------------------+
1 row in set (0.01 sec)

mysql> select is_leap_year(2021);
+--------------------+
| is_leap_year(2021) |
+--------------------+
|                  0 |
+--------------------+
1 row in set (0.00 sec)

参考URL

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?