Saturday, 31 August 2013

Display DataNames between Two Date's in SQL server...


Date Names between Two Dates:


1) Find the no.of days between two dates using DateDiff function.
      SELECT DATEDIFF(DAY,@start_date,@end_date)

2) Declare the starting count as "0", and end count is no.of days between two dates
      DECLARE @end_count INT=(SELECT DATEDIFF(DAY,@start_date,@end_date))
      
DECLARE @start_count INT=0

3) Using While loop you can iterate the function.

      
WHILE (@start_count < @end_count)
      
BEGIN  
        
--statements
      
END
 

 
Example:
 

    
DECLARE @START_DATE DATETIME='2013-06-01'

    
DECLARE @END_DATE DATETIME ='2013-06-29'

    
DECLARE @END_COUNT INT=(SELECT DATEDIFF(DAY,@START_DATE,@END_DATE))

    
DECLARE @START_COUNT INT=0DECLARE @NUMBER INT=1

    
WHILE (@START_COUNT < @END_COUNT)

    
BEGIN   

         DECLARE
@RESULT VARCHAR(1000)=(SELECT DATENAME(DW, DATEADD(DAY,@NUMBER,@START_DATE))   AS Date_Names)
        
SET @START_COUNT=@START_COUNT+1  
        
SET @NUMBER=@NUMBER+1
        
PRINT @RESULT
    
END

OutPut:


After execute the above statements the output becomes.. Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday Monday Tuesday Wednesday Thursday Friday Saturday...