>CREATE PROCEDURE dbo.usp_DDU >@ndias_calc int,@ldpontopartida datetime,@dataRetorno datetime >OUTPUT >AS >BEGIN > > if @ndias_calc=0 > BEGIN > SET @dataRetorno=cast(convert(CHAR(11),@ldpontopartida,113) as datetime) > RETURN 1 > END > > DECLARE @dtinicio datetime > DECLARE @ndias Numeric(2,0) > DECLARE @counter Numeric(2,0) > DECLARE @diautil bit > > if @ndias_calc<0 > BEGIN > SET @dtinicio=cast(convert(CHAR(11),@ldpontopartida,113) as datetime)-@ndias_calc-12 > SET @ndias=ABS(@ndias_calc)+12 > END > else > BEGIN > SET @dtinicio=cast(convert(CHAR(11),@ldpontopartida,113) as datetime) > SET @ndias=@ndias_calc+12 > END > > create table #DTodos(dia datetime, util bit) > create table #DUtil(dia datetime,util bit) > SET @counter=0 > while @counter<=@ndias > BEGIN > insert into #DTodos values(@dtinicio+@counter,case when datepart(dw,@dtinicio+@counter) between 2 and 6 then 1 else 0 end) > SET @counter=@counter+1 > END > update #Dtodos set util=0 where dia in (select dtferiado from feriado where dtferiado>=@dtinicio); > > if @ndias_calc>0 > BEGIN > insert into #Dutil select dia,util from #DTodos where util=1 or dia=@dtinicio > DECLARE @Teste Cursor > select * from #DUtil where dia=@dtinicio > if @@rowcount=0 > SET @dataRetorno=@dtinicio > else > BEGIN > DECLARE cr_dutil cursor local static for select * from #DUtil where dia>=@dtinicio > open cr_dutil > fetch first from cr_dutil into @dataRetorno,@diautil > if @diautil=0 > set @ndias_calc=@ndias_calc+1 > fetch relative @ndias_calc from cr_dutil into @dataRetorno,@diautil > close cr_dutil > deallocate cr_dutil > END > END > ELSE > BEGIN > set @dtinicio=cast(convert(CHAR(11),@ldpontopartida,113) as datetime) > insert into #Dutil select dia,util from #DTodos where util=1 or dia=@dtinicio > select * from #DUtil where dia=@dtinicio > if @@rowcount=0 > SET @dataRetorno=@dtinicio > else > BEGIN > DECLARE cr_dutil cursor local static for select * from #DUtil where dia<=@dtinicio > open cr_dutil > fetch last from cr_dutil into @dataRetorno,@diautil > if @diautil=0 > set @ndias_calc=@ndias_calc-1 > fetch relative @ndias_calc from cr_dutil into @dataRetorno,@diautil > close cr_dutil > deallocate cr_dutil > END > END > drop table #Dtodos > drop table #DUtil > RETURN 1 >END >>This sproc receive two parameters, an inicial date and a number of days and I get the date after that inicial date plus that number of days excluding weekend and holidays( the holidays I have in a table called 'feriado') as an output parameter.