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

发布于 2024-09-13 08:04:25 字数 327 浏览 4 评论 0原文

我有两个表,我想将它们合并为一个表并使用 TypeID 来区分它们。假设类型是 A 和 B。表是 A_Level 和 B_Level

A 的表看起来像

Level
Level_ID 描述

B 的表看起来像

Level
Level_ID Level_Desc

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

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

非常感谢任何帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

金兰素衣 2024-09-20 08:04:25
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;
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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文