2011年12月2日金曜日

SQL ServerのSQLで西暦を和暦に変換する方法

SQL ServerのSQLで8桁のYYYYMMDD形式の西暦を和暦に変換する。
select case
when BIRTHDAY > '19890107' then '平成'
when BIRTHDAY > '19261224' then '昭和'
when BIRTHDAY > '19120729' then '大正'
when BIRTHDAY > '18680124' then '明治'
else '0'
end 年号,
case
when BIRTHDAY > '19890107' then BIRTHDAY - 19880000
when BIRTHDAY > '19261224' then BIRTHDAY - 19250000
when BIRTHDAY > '19120729' then BIRTHDAY - 19110000
when BIRTHDAY > '18680124' then BIRTHDAY - 18670000
end 年月日
from (select '19990123' BIRTHDAY) DUMMY
実行結果は以下の通り
年号 年月日
---- -----------
平成 110123

(1 行処理されました)
年号と和暦の年月日を出力する。
このSQLでは年号を「平成」とか「昭和」という文字列で出しているが、実際はコードに変換するようなことの方が多いかもしれない。

西暦4桁の年だけで和暦に変換するには基準となる年月を定める必要がある。
select case
when BIRTHDAY >= '1989' then '平成'
when BIRTHDAY >= '1926' then '昭和'
when BIRTHDAY >= '1912' then '大正'
when BIRTHDAY >= '1868' then '明治'
else '0'
end 年号,
case
when BIRTHDAY >= '1989' then BIRTHDAY - 1988
when BIRTHDAY >= '1926' then BIRTHDAY - 1925
when BIRTHDAY >= '1912' then BIRTHDAY - 1911
when BIRTHDAY >= '1868' then BIRTHDAY - 1867
end 年
from (select '1999' BIRTHDAY) DUMMY
実行結果
年号 年
---- -----------
平成 11

(1 行処理されました)
この場合12月24日~12月31日のいずれかの日を基準とする場合には正常な結果になるが、それ以外で使うには、上記SQLの数字部分を書き換える必要がある。

0 件のコメント: