将表 2 中的所有行插入到表 1 中

Inserting into table1 for all rows in table2

我在 Group table 中有五个组,分别是 Group1、Group2、Group3、Group4、Group5,每当有新角色添加到 Role table 时,我必须进入 GROUP_ROLES table 如下

declare @gid int, @rid int
select @gid1 = id from Group where name = 'Group1'
select @gid2 = id from Group where name = 'Group2'
select @gid3 = id from Group where name = 'Group3'
select @gid4 = id from Group where name = 'Group4'
select @gid5 = id from Group where name = 'Group5'
select @rid = id from ROLE where name = 'newRole'

if @gid is not null and not exists(select * from GROUP_ROLES where group_id = @gid and roles_id = @rid)
begin
insert into GROUP_ROLES(group_id, roles_id) values (@gid1, @rid)
insert into GROUP_ROLES(group_id, roles_id) values (@gid2, @rid)
insert into GROUP_ROLES(group_id, roles_id) values (@gid3, @rid)
insert into GROUP_ROLES(group_id, roles_id) values (@gid4, @rid)
insert into GROUP_ROLES(group_id, roles_id) values (@gid5, @rid)
end

现在我有点多余的脚本。想知道有没有办法简化脚本?

试试这个:

使用 INSERT...SELECT 而不是上述所有查询将行插入到 table.

INSERT INTO GROUP_ROLES (group_id, roles_id) 
SELECT g.id, r.id
FROM Group g, ROLE r
WHERE NOT EXISTS (SELECT 1 FROM GROUP_ROLES gr WHERE gr.group_id = g.id AND gr.roles_id = r.id) AND 
      r.name = 'newRole' AND g.name IN ('Group1', 'Group2', 'Group3', 'Group4', 'Group5');