为table2中的所有行插入table1

时间:2015-01-01 13:55:33

标签: sql sql-server sql-server-2008 sql-insert

我在Group表中有五个组作为Group1,Group2,Group3,Group4,Group5,每当一个新角色添加到Role表中时,我必须进入GROUP_ROLES表如下

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

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

1 个答案:

答案 0 :(得分:1)

试试这个:

使用 INSERT ... SELECT 而不是所有上述查询来将行插入到表中。

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');