sql server - Query for updating other table while inserting data into one table -
i looking solution update , insert table2 while inserting data table1,
table1
--------------------------------------- | id |student name | % | date of exam | --------------------------------------- | 1 | tom | 80 | 12/03/2015 | | 2 | jack | 90 | 12/03/2015 | | 1 | tom | 85 | 21/05/2015 | --------------------------------------- table2 (to updated)
--------------- | id | % | --------------- | 1 | 85 | | 2 | 90 | --------------- if "id" not present in table2 want insert, , if exists, table's row should updated.
please me find solution.
thanks in advance.
if need persisted table solution, use after trigger recalculate last result every time row inserted int table1 , insert / update table2 ("lastscore") accordingly, using inserted pseudo rows.
create trigger tcalclastscore on table1 after insert, update begin delete lastscore inner join inserted on i.id = a.id; insert lastscore(id, [percent]) select id, [percent] ( select t1.id, t1.[percent], row_number() on (partition t1.id order t1.dateofexam desc) rowid table1 t1 inner join inserted on i.id = t1.id ) x rowid = 1; end; notes
- remember trigger must handle multiple
insertedrows - i've usedrow_numberfunction filter determine last row each student. - if rows can deleted first table, you'll need add trigger
on deleted, handledeletedpseudo rows well - i've been lazy , deleted + reinserted second table (
lastscore) merge possible.
however, non-persisted alternative compute last score each time on fly using view:
create view lastscore select id, [percent] ( select id, [percent], row_number() on (partition t1.id order t1.dateofexam desc) rowid table1 t1 ) x rowid = 1; the performance of view should reasonable provided there index on table1(id, dateofexam)
Comments
Post a Comment