• You can avoid a cursor.

    Create a temp table with the ID, Prod, Date and Status from the main table, and two extra columns, SetStart and SetEnd, both bit data type.

    Then run this on the temp table:

    ;with CTE (Row, Date, Prd, StatusID, SetFirst, SetLast) as

    (select row_number() over (partition by Prd order by Date),

    Date, Prd, StatusID, SetFirst, SetLast

    from #TempTable)

    update C1

    set

    SetFirst =

    case

    when C2.row is not null then 1

    else 0

    end,

    SetLast =

    case

    when C3.row is not null then 1

    else 0

    end

    from CTE C1

    left outer join CTE C2 -- The next row is a 2

    on C1.Prd = C2.Prd

    and C1.Row = C2.Row-1

    and C1.StatusID = 1

    and C2.StatusID = 2

    left outer join CTE C3 -- The prior row is a 2

    on C1.Prd = C3.Prd

    and C1.Row = C3.Row+1

    and C1.StatusID = 2

    and C3.StatusID = 1

    That should give you what you need. It may need refining, since I don't have your table structure and data to test it on, but it should be okay.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon