先輩に聞く前に、
- まずよく考えみて、
- わからなければ調べて、
- それでもダメなら聞く、
という癖をつけないとなあ。厳しいぞ。
/* Oracle PL/SQLで日付からその月の1日を求める*/
/* to_date、to_charを使えるなら、考えればできる */
create or replace function first_day(thedate date) return date is
begin
return to_date(to_char(thedate,'YYYY-MM')||'-01','YYYY-MM-DD');
end;
/* 調べてみれば、こっちがスマートだとわかる */
create or replace function first_day(thedate date) return date is
begin
return trunc(thedate,'MONTH');
end;
/***** ついでに *****/
/* 年の最初の日 1月1日 */
create or replace function first_day2(thedate date) return date is
begin
return trunc(thedate,'YEAR');
end;
/* 週の始まり日曜日(※NLSの設定次第) */
create or replace function first_day3(thedate date) return date is
begin
return trunc(thedate,'DAY');
end;
最後に問題。月の日数を求めるにはどうする?
NLSはクライアント単位でカスタムできちゃうので、勝手に変更されない保障があるのならNLS依存でも構わないと思います。(あるいはアプリ起動時にALTER SESSIONで毎回設定するとか)
お目汚し失礼しました。
thedate + (1 – to_char(thedate, ’D’))
とするとNLSに依存しないで週の頭の日付が取れるかもしれません。
ちゃんと検証してないのでアレですが。