Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

Update table that references duplicates Sql Server

I have two tables Table A and Table B. I need Table A to reference Table B but I first need to delete the duplicates of Table B and have Table A reference the new ID.

At the moment I am able to partition the records using WITH TIES but how do I ensure that each record points to the correct reference?

Example:

Table A
Name RefId
Item 1 251
Item 2 251
Item 3 167
Item 4 75
question from:https://stackoverflow.com/questions/65623782/update-table-that-references-duplicates-sql-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use UPDATE in tableA first then delete duplicate from TableB as follows:

update tableA A
set A.ref_id = 
     (select max(ref_id) 
        from tableB 
       where name in (select name 
                        from tableB B 
                       where B.ref_id = A.ref_id))

delete from tableB B
 where exists 
       (select 1 from tableB BB
         where BB.NAME = B.NAME
           AND BB.ref_id > B.ref_id)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...