I have a timesheet table records stored as follows in DetailsTbl
:
ID | Day | hours
----------------------------
1 | 14/feb/14 | 8
1 | 15/feb/14 | 8
And table called PAssign
as follows:
ID | from | to
----------------------------------
1 | 14/feb/14 | 17/feb/14
By executing the stored procedure, output should show:
ID | from | to | day | Hours
------------------------------------------------
1 | 14/feb/14 | 17/feb/14 | 14/feb/14 | 8
1 | 14/feb/14 | 17/feb/14 | 15/feb/14 | 8
1 | 14/feb/14 | 17/feb/14 | 16/feb/14 | 0
1 | 14/feb/14 | 17/feb/14 | 17/feb/14 | 0
Only the null values where day between the from / to should be set to default which is ' 0 '
help appreciated
Taking a range and exploding it into multiple records can be done with a recursive CTE or a Numbers table . Here is an example using a recursive CTE:
;with cte as (
select [id], [from], [to], [from] as day from PAssign
union all
select [id], [from], [to], [day]+1 from cte
where [day] < [to]
)
select
cte.id, cte.[from], cte.[to], cte.[day],
coalesce(d.hours, 0) as hours
from cte
left join DetailsTbl d on cte.id = d.id and cte.day = d.day
Results ( DEMO )
| ID | FROM | TO | DAY | HOURS |
|----|---------------------------------|---------------------------------|---------------------------------|-------|
| 1 | February, 14 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | February, 14 2014 00:00:00+0000 | 8 |
| 1 | February, 14 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | February, 15 2014 00:00:00+0000 | 8 |
| 1 | February, 14 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | February, 16 2014 00:00:00+0000 | 0 |
| 1 | February, 14 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | February, 17 2014 00:00:00+0000 | 0 |
Turning this into a stored procedure should be pretty easy. Also note that a Recursive CTE makes use of one level of recursion per record generated, so you'll need to set the maximum recursion level as appropriate.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.