tsql dates

arkiboys 9,641 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

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

Accepted answer
  1. Viorel 112.5K 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,176 Reputation points
    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