Custom Date Column

ali mohammed 46 Reputation points
2022-09-10T05:42:51.1+00:00

Hi

i have question

i want to create column "hrdate" its starts next month from 21 of each month and ends in 20
Could you help me with SQL query

239731-image.png

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

Accepted answer
  1. Tom Cooper 8,466 Reputation points
    2022-09-10T06:18:28.947+00:00
    -- Declare table with computed columns  
    Declare @Sample Table(  
      TheDate date,   
      Month As DateName(month, TheDate),   
      HRMonth As DateName(month, Case When Day(TheDate) <= 20 Then TheDate Else DateAdd(Month, 1, TheDate) End)  
      );  
      
    -- Load dates in table  
    ;With cte As  
    (Select Cast('20220901' As date) As TheDate  
    Union All  
    Select DateAdd(day, 1, TheDate) From cte  
    Where TheDate <= '20221022')  
    Insert @Sample(TheDate) Select TheDate From cte;  
      
    -- Check that computed columns have desired values  
    Select TheDate, Month, HRMonth From @Sample;  
    

    Tom

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Viorel 116.7K Reputation points
    2022-09-10T06:17:05.713+00:00

    Try something like this:

    select [day in month], [month],  
        lower(datename(month, dateadd(month, iif([day in month] > 20, 1, 0), cast('2000-' + [month] + '-1' as date)))) as hrmonth  
    from MyTable  
    
    0 comments No comments

Your answer

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