SQL Server存储过程返回不存在的临时记录

时间:2014-03-23 21:05:57

标签: sql sql-server

我在DetailsTbl

中按如下方式存储了时间表表记录
ID   |  Day        | hours
----------------------------
 1   | 14/feb/14   |   8
 1   | 15/feb/14   |   8

表格PAssign如下:

 ID | from      | to
----------------------------------
 1  | 14/feb/14 | 17/feb/14

通过执行存储过程,输出应显示:

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

只有 / 之间的的空值应设置为默认值<&39; 0 &#39;

帮助赞赏

1 个答案:

答案 0 :(得分:0)

可以使用recursive CTENumbers table获取范围并将其展开为多个记录。以下是使用递归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

结果(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 |

将其转换为存储过程应该非常简单。另请注意,递归CTE使用每个记录生成的一级递归,因此您需要根据需要设置maximum recursion level