• Hmmm... Strange requirement indeed. If I'm understanding this correctly, a quirky update might do it.

    Set up your table like this:

    create table #abc

    (insertid int, cityid int, parentcityid int, cityname varchar(50), parentname varchar(50)

    ,PRIMARY KEY CLUSTERED (insertid, cityid, parentcityid))

    insert into #abc

    select 1,10,11,'A','B'

    union all select 1,11,12,'B','C'

    union all select 1,12,13,'C','D'

    union all select 2,10,11,'A','B'

    union all select 2,11,13,'B','D'

    union all select 2,12,11,'C','A'

    Then try this, but test it thoroughly against deeper cases to be sure that it works. It seems to for this limited test data anyway.

    DECLARE @NextParentID INT = 0, @CityID INT = 0

    UPDATE a

    SET @NextParentID = CASE WHEN parentcityid >= @NextParentID THEN parentcityid + 1

    WHEN CityID >= @NextParentID THEN CityID + 1

    ELSE @NextParentID END

    ,@CityID = CityID = CASE WHEN (

    SELECT CityID

    FROM #abc b

    WHERE b.InsertID = a.InsertID - 1 AND b.cityid = a.cityid AND

    b.parentcityid <> a.parentcityid) IS NULL

    THEN CityID ELSE CASE WHEN @CityID >= @NextParentID THEN @CityID + 1 ELSE @NextParentID END END

    FROM #abc a

    OPTION (MAXDOP 1)

    SELECT * FROM #abc

    DROP TABLE #abc


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St