Question

I have table: T1 (ID BIGINT, NAME NVARCHAR(1000))

Data:

select * from T1
1, AAA
2, BBB
3, CCC
4, DDD

The RELATIONS_T (ID, T1_ID1,T1_ ID2) table holds relationships between ID’s from T1 table.

SELECT * 
FROM RELATIONS_T

Output:

ID, T1_ID1,T1_ ID2
1,    1,   2 

In this table 1 is connected to 2

The RELATIONS_LOG_TABLE (ID, OLD_ID, NEW_ID, OLD_STUFF_ID, NEW_STUFF_ID) has columns OLD_STUFF_ID and NEW_STUFF_ID that are not important for my question.

Select ID, OLD_ID, NEW_ID 
from RELATIONS_LOG_TABLE

Output:

ID, OLD_ID, NEW_ID
1, 1, 3
2, 2, 4

This means that 1 becomes 3, and 2 becomes 4

How can I check from table RELATIONS_LOG_TABLE and RELATIONS_T that there is connections between 1 and 2, and manually enter in table RELATIONS_T 3, 4.

Était-ce utile?

La solution

The following statement would insert the tuples

3,2 (1 replaced by 3)
1,4 (2 replaced by 4)
3,4 (both replaced)
insert into relations_t (id1, id2)
  select coalesce(rep1.new_id, id1), coalesce(rep2.new_id, id2)
  from relations_t r
  left join relations_log_table rep1 on rep1.old_id = r.id1
  left join relations_log_table rep2 on rep2.old_id = r.id2
  where rep1.id is not null or rep2.id is not null;

If you only want the "best" record (both replaced if this is the case, else one replaced), you must get the top record according to number of replacements.

insert into relations_t (id1, id2)
  select top(1) coalesce(rep1.new_id, id1), coalesce(rep2.new_id, id2)
  from relations_t r
  left join relations_log_table rep1 on rep1.old_id = r.id1
  left join relations_log_table rep2 on rep2.old_id = r.id2
  where rep1.id is not null or rep2.id is not null
  order by case when rep1.id is not null and rep2.id is not null then 0 else 1 end;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top