根据另一个表更新表中的数据

时间:2019-03-06 09:06:51

标签: sql-server

我的问题相对简单,但我正在寻找最佳方法。

我的数据库中有3个表:New_Training,Old_Training和Conversion。它们的结构如下:

New_Training

User_Nr    NewTraining_Nr
112233        10
223344        10
445566        11

Conversion

NewTraining_Nr   OldTraining_Nr
10                  8430
10                  8650
10                  8900
11                  9430
11                  9500

Old_Training (This is how it should look)

User_Nr   OldTraining_Nr   OldTrainingNr_Lvl
112233        8430               1
112233        8650               1
112233        8900               1
223344        8430               1
223344        8650               1
223344        8900               1
445566        9430               1
445566        9500               1

我想编写一个SQL脚本,检查New_Training表以查看是否有用户以及与他们关联的是哪个NewTraining_Nr,通过使用Conversion表将NewTraining_Nr转换为OldTraining_nr,然后将值1插入到OldTrainingNr_Lvl列中该用户对应的OldTraining_Nr,更新表。

如果用户是新用户(在New_Training内部),则应将User_Nr以及相应的OldTraining_Nr和级别1添加到Old_Training表中。

此脚本应该是动态的,因为它不应依赖于User_nr,而应循环遍历New_Training表内的User_Nr。

2 个答案:

答案 0 :(得分:0)

如果您想使用前2个表的结果插入第3个表,则可以这样做

declare @New_Training table (User_Nr int, NewTraining_Nr int)
declare @Conversion table (NewTraining_Nr int, OldTraining_Nr int)
declare @Old_Training table (User_Nr int, OldTraining_Nr int, OldTrainingNr_Lvl int)

insert into @New_Training (User_Nr, NewTraining_Nr)
values (112233, 10), (223344, 10), (445566, 11)

insert into @Conversion (NewTraining_Nr, OldTraining_Nr)
values (10, 8430), (10, 8650), (10, 8900), (11, 9430), (11, 9500)

insert into @Old_Training (User_Nr, OldTraining_Nr, OldTrainingNr_Lvl)
select nt.User_Nr,
       c.OldTraining_Nr,
       1
from   @New_Training nt
  left join @Conversion c on nt.NewTraining_Nr = c.NewTraining_Nr

select * from @Old_Training 

这将产生此结果

User_Nr OldTraining_Nr  OldTrainingNr_Lvl   
------- --------------  -----------------   
112233      8430            1   
112233      8650            1   
112233      8900            1   
223344      8430            1   
223344      8650            1   
223344      8900            1   
445566      9430            1   
445566      9500            1   

答案 1 :(得分:0)

Insert into Old_Training (User_Nr, OldTraining_Nr, OldTrainingNr_Lvl)
select nt.User_Nr,
       c.OldTraining_Nr,
       1 as OldTrainingNr_Lvl
from New_Training nt
  left join Conversion c on nt.NewTraining_Nr = c.NewTraining_Nr