views:

28

answers:

1

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 merge the two tables into one table (Level_Code) and update the referenced Tables ID's accordingly.

Any help is greatly appreciated.

+1  A: 
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;
Michael Pakhantsov
Im getting Incorrect syntax near the keyword 'AS'. From the second line of the query as well as after reate Table YourNewTable
Gage
@Gage, I have updated script
Michael Pakhantsov