OTUser
OTUser

Reputation: 3848

Inserting into table1 for all rows in table2

I have five groups in Group table as Group1, Group2, Group3, Group4, Group5 and whenever a new role added into Role table I have to make an entry into GROUP_ROLES table as below

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

Right now I kinda have redundant script. Am wondering is there a way to simplify the script?

Upvotes: 1

Views: 67

Answers (1)

Saharsh Shah
Saharsh Shah

Reputation: 29051

Try this:

Use INSERT...SELECT instead of all above queries to INSERT rows in to 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');

Upvotes: 1

Related Questions