ずっと気がかりなことがありました。
そもそも四半期の計算にループ要るのかなぁって
dbo.fiscalyear
CREATE FUNCTION dbo.fiscalyear(
@Date Datetime2,
@ClosingMonth int = 3)
returns @FiscalElements table
~~
--This part sets fiscalyear of @Date.
--この部分で会計年度をセット
if(@innermonth > @ClosingMonth)
set @inneryear = year(@date);
else
set @inneryear = year(@date) - 1;
--This part sets quarterpart of @Date.
--この部分で四半期をセット
declare @repeatmonth as int;
set @repeatmonth = 0;
declare @relativemonth as int;
set @relativemonth = dbo.MonthCorretion(@ClosingMonth +@repeatmonth + 1);
declare @quarterpart int;
while @repeatmonth < 13
begin
if (@relativemonth = @innermonth)
begin
set @quarterpart = cast((@repeatmonth / 3) as int)+1;
break;
end
else
begin
set @repeatmonth = @repeatmonth + 1;
set @relativemonth = dbo.MonthCorretion(@relativemonth + 1);
continue;
end
end
これを少しリファクタリングします。ループなしで実装しなおすと
dbo.fiscalyear2
--This part sets fiscalyear and quarterpart from @Date.
--この部分で会計年度と四半期をセット
declare @relativemonth as int;
declare @quarterpart as int;
if (@innermonth > @ClosingMonth)
begin
set @inneryear = year(@date);
set @relativemonth =(@innermonth -@ClosingMonth-1);
end
else
begin
set @inneryear = year(@date) - 1;
set @relativemonth =(11 + @innermonth -@ClosingMonth);
end
set @quarterpart = cast((@relativemonth / 3) as int)+1;
これでループを排除できたことになる。
このループを排除したfiscalyearの全文を並べると
dbo.fiscalyear2
CREATE FUNCTION dbo.fiscalyear(
@Date Datetime2,
@ClosingMonth int = 3)
returns @FiscalElements table
(
date Datetime2 Not null,
fiscalyear int Not null,
quarterpart int Not null,
quarterparthanji char(18) Not null
)
as
begin
declare @innermonth as int;
declare @inneryear as int;
set @innermonth = month(@Date);
--This part sets fiscalyear and quarterpart from @Date.
--この部分で会計年度と四半期をセット
declare @relativemonth as int;
declare @quarterpart as int;
if (@innermonth > @ClosingMonth)
begin
set @inneryear = year(@date);
set @relativemonth =(@innermonth -@ClosingMonth-1);
end
else
begin
set @inneryear = year(@date) - 1;
set @relativemonth =(@innermonth -@ClosingMonth -1 +12);
end
set @quarterpart = cast((@relativemonth / 3) as int)+1;
--this part sets japanese quaterpart in character.
--この部分では文字列四半期を設定する。
declare @qparthanzi char(2);
if (@quarterpart=1) set @qparthanzi = '壱'
if (@quarterpart=2) set @qparthanzi = '弐'
if (@quarterpart=3) set @qparthanzi = '参'
if (@quarterpart=4) set @qparthanzi = '肆'
insert @FiscalElements(date,fiscalyear,quarterpart,quarterparthanji)
values (@Date,@inneryear,@quarterpart,cast(@inneryear as char(4)) + '年度第' + @qparthanzi + '四半期')
return
end
以上