循环表以更新重叠日期范围

时间:2015-12-06 09:51:49

标签: sql sql-server tsql sql-server-2012

我有两个表,它是源表和目标表,如下所示:

原始来源表:

ID MemberID StartDate EndDate Status
1  1        2015-02-02 2015-05-05 0
2  2        2015-02-02 2015-05-05 0
3  1        2015-03-03 2015-06-06 0
4  1        2015-04-04 2015-06-06 0
5  1        2016-01-01 2016-02-02 0
6  3        2015-01-01 2015-03-03 0

原始目的地表:

ID MemberID StartDate  EndDate
1  1        2015-03-02 2015-05-05
2  2        2015-04-02 2015-05-05
3  1        2016-01-02 2016-04-03
4  3        2015-01-01 2015-03-01
5  3        2015-03-03 2015-04-03

输出源表

ID MemberID StartDate  EndDate    Status
1  1        2015-02-02 2015-05-05 2(updated)
2  2        2015-02-02 2015-05-05 2(updated)
3  1        2015-03-03 2015-06-06 2(updated)
4  1        2015-04-04 2015-06-06 2(updated)
5  1        2016-01-01 2016-02-02 1(inserted)
6  3        2015-01-01 2015-03-04 3(fail)

输出目的地表

ID MemberID StartDate  EndDate    
1  1        2015-02-02 2015-06-06
2  2        2015-02-02 2015-05-05
3  1        2016-01-02 2016-04-03
4  3        2015-01-01 2015-03-01
5  3        2015-03-03 2015-04-03    
6  1        2016-01-01 2016-02-02

假设:具有相同memberID的目标表日期范围永远不会重叠。
sql的伪代码如下。怎么可能实现?

foreach (var i in SourceTable)
{
  foreach(var j in DestinationTable with same memberid as i)
  {
    if (i daterange overlap with only 1 j date range)
        {
                update DestinationTable date range to new date range by taking min and max date for both src and target
                update SrcTable Status to 2
        }
        else if (i daterange overlap with more than 1 j date range)
        {
               update SrcTable Status to 3
        }
        else if (i do no overlap with any date range in j)
        {
               insert i to destination table
               update SrcTable Status to 1
        }
  }

0 个答案:

没有答案