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 table
  • employeetaskdefinitions table has 6 rows ids 1-6
  • employeetasks 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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -