SQL合并两个表并更新引用的ID

时间:2010-08-10 14:40:13

标签: sql sql-server-2000

我有两个表要加入一个表并使用TypeID来区分它们。假设类型是A和B.表是A_Level和B_Level

A的表格看起来像

等级
Level_ID描述

B的表格看起来像

等级
Level_ID Level_Desc

A的Level_ID从表C引用为Level_ID
B的Level_ID从表D引用为Level_ID

我正在寻找一个将两个表合并为一个表(Level_Code)的脚本,并相应地更新引用的表ID。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

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;