Sunday, June 12, 2016

Looping through resutset in Table Valued Function

Database CASKoenigDB

alter function [dbo].[getFullMonthforRC](@TrainerID int,@CourseSDate datetime,@CourseEDate datetime,@LocationId int,@weekendstatus varchar(30),@courselist nvarchar(max)) 
returns  @TableofDates table(TrainerID int not null,trngdate datetime not null,locationid int not null) 
Begin 
declare @trnid int 
declare @lnid int 
Declare @startDate datetime 
declare @weekendbatch varchar(30)
Declare @interestedCourses nvarchar(max)
Declare @excluddates  datetime  
Declare @dateval  datetime
Declare @Count int
Declare @Loopcount int
Declare @endDate datetime
set @trnid=@TrainerID 
set @startDate=@CourseSDate 
 
set @endDate=@CourseEDate 
set @lnid=@LocationId 
set @weekendbatch=@weekendstatus 
set @interestedCourses=@courselist
  While (@startDate<=@endDate) begin
  if exists(Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses)
  begin
  --counting total records
   Select @Count=count(*) from dbo.Split ( (Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses),';')
   Set @Loopcount=1
   While  @Loopcount<=@Count
   begin
    Select @dateval=items from( Select *,ROW_NUMBER()over(Order by items)ID from dbo.Split ( (Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses),';') ) RC where ID=@Loopcount 
   
    Set @Loopcount=@Loopcount+1
    if (@dateval=@startDate)  begin
      
       set @startDate=DATEADD(DAY, 1, @startDate)
    end
   
   end
   if  (@startDate<=@endDate) begin
     --print @startDate
     INSERT INTO @TableOfDates(TrainerID,trngdate,locationid) VALUES (@trnid,@startDate,@lnid) 
     set @startDate=DATEADD(DAY, 1, @startDate)
   end
  end
  else if not exists(Select  cast (ExcludedDate as nvarchar(max))  from TRAN_EXCLUDEDAY where InterestedCourseId=@interestedCourses )begin 
    --print @startDate
    INSERT INTO @TableOfDates(TrainerID,trngdate,locationid) VALUES (@trnid,@startDate,@lnid) 
    set @startDate=DATEADD(DAY, 1, @startDate)
  end 
end   
  
return 
End 

No comments:

Post a Comment