sql server - How to insert rows into a table based on another table's rows using Triggers? -
i have 3 tables:
employee
id firstname lastname employeetasksid
employeetasks
id employeeid employeetaskdefinitionid
employeetaskdefinitions
id description etc.
what trying once employee
inserted employees
table, need insert rows employeetasks
table based on inserted employee's
id , every employeetaskdefinition's id.
for example:
employee
id
1 inserted employee tableemployeetaskdefinitions
table has 6 rowsids
1-6employeetasks
table needs have 6 rows after insert:id = 1, employeeid = 1, employeetaskdefinitonid = 1 id = 2, employeeid = 1, employeetaskdefinitonid = 2 id = 3, employeeid = 1, employeetaskdefinitonid = 3 id = 4, employeeid = 1, employeetaskdefinitonid = 4 id = 5, employeeid = 1, employeetaskdefinitonid = 5 id = 6, employeeid = 1, employeetaskdefinitonid = 6
now have read numerous posts cursors, people saying they're bad practice use task. how this? note: don't want use else other triggers.
edit: query came with.
create trigger createemployee on [dbo].[employeeset] after insert declare @loopcounter int, @maxsettingdefinitionid int, @id int select @loopcounter = min(id), @maxsettingdefinitionid = max(id) settingsdefinitionset while(@loopcounter not null , @loopcounter <= @maxsettingdefinitionid) begin select @id = id settingdefinitionset id = @loopcounter insert settingset(companyid, employeeid, settingdefinitionid, settingtype, state, value) values((select companyid inserted), (select id inserted), @id, (select settingtype settingset employeeid null , companyid = (select companyid inserted) , settingdefinitionid = @id), (select state settingset employeeid null , companyid = (select companyid inserted) , settingdefinitionid = @id), (select value settingset employeeid null , companyid = (select companyid inserted) , settingdefinitionid = @id)) select @loopcounter = min(id) settingdefinitionset id > @loopcounter end go
this should trick:
insert employeetasks(employeeid, employeetaskdefinitionid) select inserted.id employeeid, t.id employeetaskdefinitionid inserted join employeetaskdefinitions
Comments
Post a Comment