Tuesday, June 7, 2016

Function in sql for removing weekend

ALTER Function [dbo].[calculateTotalTestData11](@interestCourseId int)   
returns nvarchar(max) --@temptable TABLE (dates datetime)      
AS   
BEGIN  
DECLARE @stDate DateTime;
DECLARE @endDate DateTime;
DECLARE @Location int;
SELECT @stDate=CourseSDate,@endDate=CourseEDate,@Location=LocationId from TRAN_SCINTERESTEDCOURSES where InterestedCourseId=@interestCourseId;
DECLARE @temptable table(dates datetime) ;
; WITH CTE(dt) 
 AS 
 (  
 SELECT @stDate 
 UNION ALL 
 SELECT DATEADD(D,1,dt) FROM CTE 
 where dt < @endDate 
 ) 
  insert into @temptable(dates) 
 select dt  from CTE where (CASE WHEN @location = 5  
 THEN (CASE WHEN DATENAME(dw, dt) = 'FRIDAY' THEN 1 ELSE 0 END)  
 ELSE  ( 
 CASE WHEN @location = 8 OR @location = 9
 THEN ((CASE WHEN DATENAME(dw, dt) = 'SATURDAY' OR  DATENAME(dw, dt) = 'SUNDAY'  THEN 1 ELSE 0 END)) 
 ELSE (CASE WHEN DATENAME(dw, dt) = 'Sunday' THEN 1 ELSE 0 END)  END) 
 END )=1 and dt <> @stDate and dt <>@endDate;
  
 return   STUFF((SELECT DISTINCT '; ' + CONVERT(nvarchar(11),dates,113) FROM @temptable FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')


END

No comments:

Post a Comment