sql server而日期不是周末或特定日期

时间:2017-01-05 13:26:48

标签: sql sql-server

我正在尝试编写一个sql while循环来增加一个日期,直到它不与另外两个表中的日期交配,而不是星期六或星期日。

像这样的东西

DECLARE @DueDate datetime
SELECT @DueDate = datetime FROM tbl_status WHERE (parent_id = @ComplaintId)
WHILE((SELECT COUNT(date) FROM tbl1 WHERE(date = @DueDate)) > 0 AND (SELECT COUNT(date) FROM tbl2  WHERE(date = @DueDate)) > 0 AND DATEPART(d,@DueDate) = 'Saturday' AND  DATEPART(d,@DueDate) = 'Sunday')
BEGIN
    @DueDate = DATEADD(d,1,@DueDate)
END

任何人都可以提供帮助

感谢

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的那样,你使用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