Skip to content
Advertisement

Dynamic Dates SQL Server

I have the below data in SQL.

I need to figure out a way dynamically to get the next dates based the 2 values below. The remaining doses tells me how many dates I will need to find and RXDAYS tells me the increments in which to look for the dates

So based on the above I would find the date 30 days after 2019-06-05 and get 2019-07-05 and 30 days after that I would get 2019-08-04.

Is there a way to do this?

Advertisement

Answer

Use dateadd(). This gives you the final date:

On the other hand if you want to generate new rows, then you could use a recursive query:

For the sample data row showned in your question, this would generate three rows, with dates 2019-06-05, 2019-07-05 and 2019-08-04.

If doses has values greater than 100, then you need to add option(maxrecursion 0) at the very end of the query.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement