Today I have a problem with splitting a date range so it becomes two separate records.
Here is an example
----------------------------------------------------------------
| Record id | date_from | date_to |
----------------------------------------------------------------
| A | 2017-02-03 08:00:00.000 | 2017-02-04 17:00:00.000|
----------------------------------------------------------------
For the result I want this
----------------------------------------------------------------
| Record id | date_from | date_to |
----------------------------------------------------------------
| A | 2017-02-03 08:00:00.000 | 2017-02-03 23:59:59.000|
----------------------------------------------------------------
| A | 2017-02-04 00:00:00.000 | 2017-02-04 17:00:00.000|
----------------------------------------------------------------
Is there anything that can enlighten me with this problem? Thank you very much for your advice.
PS: this is dynamic and there is no limit in duration. If the "from" day is 2017-02-02 at 17:00, and the "to" day is 2017-02-04 17:00 then there will be three records, one of which is date range from 2017-02-03 00:00:00 until 2017-02-03 23:59:59.
For midnight, I guess it is based on the date time default. For the real problem, I have this table:
As you can see, from the detail for seeding mailbox databse, the range is like one day as assumption, so I guess it is more like that example 🙂
PS: I am using SQL Server 2014.
Best Answer
One way to do it is to use a table of numbers and
CROSS APPLY
.Sample data
Query
In this example I generated a table of 10 numbers on the fly (
CTE_Numbers
). In production I have a permanent table with 100K numbers.Result