shilpa krishnamraju
shilpa krishnamraju

Reputation: 11

How to split time into hourly slot using SQL (can use view,or stored proc or function)

Example I have data in table which has start date, end date and duration. I want to show hourly time slot.

logic:

How can I achieve this in Sql Server?

Upvotes: 1

Views: 346

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269533

I assume that your issue is getting multiple rows from one, rather than formatting the date/time values as a string.

For this, you can use a recursive CTE:

with cte as (
      select startdate as thetime, t.*
      from t
      union all
      select dateadd(hour, 1, cte.startdate), . . .  -- rest of columns here
      from cte
      where cte.thetime < cte.enddate
     )
select cte.*
from cte;

You can then format thetime however you like, including the hyphenated version in your question.

SQL Server has a default limit of 100 for recursion -- the number of rows produced. Your example only uses times, so this can't exceed 24 and is not an issue. However, it could be an issue in other circumstances in which case option (maxrecursion 0) can be added to the query.

Upvotes: 1

Related Questions