を助けることができる、あなたは、whileループと非常に非効率的な方法で、これについてうとしています。
あなたは、ルックアップで使用する日付のテーブルを持っていない場合、あなたはそれ以外の共通テーブル式として知られる派生テーブルを持つものを、作成することができます。
-- Set up the test data:
declare @t1 table (d date);
declare @t2 table (d date);
insert into @t1 values('20161230'),('20170111'),('20170110');
insert into @t2 values('20161225'),('20170105'),('20170106');
-- Declare your DueDate:
declare @DueDate date = '20170105';
-- Use a CTE to build a table of dates. You will want to set the Start and End dates automatically with SELECT statements:
declare @DatesStart date = '20161201';
declare @DatesEnd date = '20170225';
with Tally0 as
(
select x from (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) as x(x)
)
,Tally1 as
(
select row_number() over (order by (select null))-1 as rn
from Tally0 t1 -- 10 rows -- Add more CROSS APPLY joins
cross apply Tally0 t2 -- 100 rows -- to get enough rows to cover
cross apply Tally0 t3 -- 1000 rows -- your date range.
)
,Dates as
(
select dateadd(d,t.rn,@DatesStart) as DateValue
from Tally1 t
where t.rn <= datediff(d,@DatesStart,@DatesEnd)
)
select min(d.DateValue) as NextDate -- SELECT the next available Date.
from Dates d
left join @t1 t1
on(d.DateValue = t1.d)
left join @t2 t2
on(d.DateValue = t2.d)
where t1.d is null -- That isn't in either table
and t2.d is null -- and isn't on a Saturday or Sunday.
and datename(weekday,d.DateValue) not in('Saturday','Sunday')
and d.DateValue > @DueDate
そして、問題がありますか? – Sachin
このためにループを使用すべきではありません。他の2つのテーブルまたは土曜日/日曜日にない、ソース日付よりも大きい最小日付を検出するセットベースを使用する必要があります。 – iamdave