mssql sqlserver 获取sql两个日期之间的天数差–并排除其中所包含的周末


摘要:
下文讲述使用sql函数的方法获取两个日期之间的天数差,如下所示:
实验环境:sql server 2008 R2


实现思路:
使用while循环遍历两个日期之间,并获取天数差。

     create function fn_dateRangeGet(@d1 datetime,@d2 datetime)
    returns int 
     begin
        declare @i int =0 
          if @d1 is null or @d2 is null 
          begin
             set @i =-99
             return @i 
          end

         if @d1 >@d2 
         begin
             set @i=-1 
             return @i  
         end
         
        while @d1 <@d2 
        begin
             declare @xingQiLiu   dateTime 
             declare @xingQiTian dateTime
             set @xingQiLiu  =N'2019-6-29'
             set @xingQiTian =N'2019-6-30'
     
             if  weekday(@d1)  = weekday(@xingQiLiu)   or    weekday(@d1)  = weekday(@xingQiTian) 
              begin
                   set @d1 =dateadd(day,1,@d1)           
               end
               else
               begin
                   set @d1 =dateadd(day,1,@d1)     
                   set @i= @i+1
               end
        end
         
        return @i 
     end