开发者

SQL merging two tables and updating referenced IDs

I have two tables that I want to join into one table and use a TypeID to differentiate them. Let's say the types are A and B. The Tables are A_Level and B_Level

A's Table looks like

Level

Level_ID Description

B's Table looks like

Level

Level_ID Level_Desc

A's Level_ID is referenced from Table C as Level_ID

B's Level_ID is referenced from Table D as Level_ID

I am looking for a script that would 开发者_StackOverflow社区merge the two tables into one table (Level_Code) and update the referenced Tables ID's accordingly.

Any help is greatly appreciated.


select a.Level_Id ALevelId, b.Level_Id BLevelId, 
       case ISNULL(a.Level_Id, 0) when 0 then 'B' else 'A' end AS Type,
       case ISNULL(a.Level_Id, 0) when 0 then b.Level_Id else a.Level_Id end AS NewLevel_Id
INTO Dummy       
FROM  a 
FULL JOIN  b On (a.Level_ID = b.Level_ID); 


UPDATE c
SET c.Level_id = Dummy.NewLevel_Id
from Dummy, c
WHERE c.Level_Id = Dummy.ALevelId 
AND Dummy.Type = 'A';

UPDATE d
SET d.Level_id = Dummy.NewLevel_Id
from Dummy, d
WHERE d.Level_Id = Dummy.BLevelId 
AND Dummy.Type = 'B';

SELECT Dummy.NewLevel_Id, a.Level, a.LevelDesc As Description
INTO YourNewTable
from Dummy JOIN a ON (Dummy.ALevelId = a.Level_Id)
Where Dummy.Type = 'A'
UNION
SELECT NewLevel_Id, Level, LevelDesc As Description
from Dummy JOIN b ON (Dummy.BLevelId = b.Level_Id)
Where Dummy.Type = 'B'

DROP TAble Dummy;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜