Translate

> > SQL Date Loop For Each Month

SQL Date Loop For Each Month

Posted on Thursday, July 2, 2020 | No Comments


 DECLARE @FromDate DATETIME
 SET @FromDate='01/01/2020'

 DECLARE @ToDate DATETIME
 SET @ToDate= CONVERT(DATETIME, CAST(  DATEPART(MONTH,GETDATE()) AS NVARCHAR(50) ) + '/01/' + CAST( DATEPART(YEAR,GETDATE()) AS NVARCHAR(50)) ,101 )

 DECLARE @TableName NVARCHAR(50)

 WHILE (@FromDate <= @ToDate)
 BEGIN

     SET @TableName = 'Sales'+ CAST( DATEPART(YEAR,@FromDate) AS NVARCHAR(50)) + RIGHT('00'+ISNULL( CAST( DATEPART(MONTH,@FromDate) AS NVARCHAR(50)) ,''),2)
     PRINT @TableName

     SET @FromDate = DATEADD(MONTH,1,@FromDate)
 END

Leave a Reply

Powered by Blogger.