• scottichrosaviakosmos (8/8/2012)


    create table #abc(insertid int,cityid int,parentcityid int,cityname varchar(50),parentname varchar(50))

    insert into #abc

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

    union

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

    union

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

    union

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

    union

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

    union

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

    Output:

    Insertid Cityid Parentid cityname parentname

    1 10 11 AB

    1 11 12 BC

    1 12 13 C D

    2 10 11 A B

    2 11 13 B D

    2 12 11 C A

    Where ever there is a change in parent for same child for different insertid then there should be a new id assign to old id. Eg: in table for insertid 1 cityid 11 had parent c(id=12) but for insertid 2 cityid 11 has parented as13 . So the desired output should be like:

    Insertid Cityid Parentid cityname parentname

    1 10 11 A B

    1 11 12 B C

    1 12 13 C D

    2 10 11 A B

    2 14 13 B D

    2 15 11 C A

    I think now the post will be clear.

    We now have a clean table of sample data. Your desired output looks exactly like select * from #abc so I assume that is what that is.

    However, you tried to explain what you want and it doesn't make any sense.

    Where ever there is a change in parent for same child for different insertid then there should be a new id assign to old id. Eg: in table for insertid 1 cityid 11 had parent c(id=12) but for insertid 2 cityid 11 has parented as13 .

    What does that mean? And what do you want? Do you want a trigger on this table that an update based on some rules that are still unclear (at least to me)? What is cityid? And what is the rule here? Does this table even have a primary key?

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/