question

arkiboys avatar image
0 Votes"
arkiboys asked MelissaMa-msft edited

tsql dates

Hello, In TSQL, how can I check if the current date is: 1- First day of the current month 2- First day of the current year Thank you

sql-server-transact-sql
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered Viorel-1 edited

Check an example:

 declare @date as date = ... some date ...
    
 if DATEPART(day, @date) = 1 and DATEPART(month, @date) = DATEPART(month, GETDATE())
     PRINT 'First day of current month'
    
    
 if DATEPART(day, @date) = 1 and DATEPART(month, @date) = 1 and DATEPART(year, @date) = DATEPART(year, GETDATE())
     PRINT 'First day of current year'

In case of current date:

 declare @date as date = GETDATE()
    
 if DATEPART(day, @date) = 1 
     PRINT 'First day of current month'
    
    
 if DATEPART(day, @date) = 1 and DATEPART(month, @date) = 1
     PRINT 'First day of current year'
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

MelissaMa-msft avatar image
0 Votes"
MelissaMa-msft answered MelissaMa-msft edited

Hi @arkiboys,

Welcome to Microsoft Q&A!

Please refer below:

 declare @date date
    
 set @date=GETDATE() --or change to another date
    
 SELECT case when @date=DATEADD(month, DATEDIFF(month, 0, @date), 0) then 'First day of the current month' else 'Not First day of the current month' end,
 case when @date=DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) then 'First day of the current year' else 'Not First day of the current year' end

If above is not working,we recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data, enough to illustrate all angles of the problem. We also need to see the expected result of the sample.

Best regards
Melissa


If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.