tsql dates

arkiboys 9,711 Reputation points
2021-03-24T07:59:46.427+00:00

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

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Viorel 126.1K Reputation points
    2021-03-24T08:08:10.493+00:00

    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'  
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. MelissaMa-msft 24,246 Reputation points Moderator
    2021-03-24T08:09:16.807+00:00

    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.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.