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; 

sqlfiddle here

notes

  • remember trigger must handle multiple inserted rows - i've used row_number function filter determine last row each student.
  • if rows can deleted first table, you'll need add trigger on deleted , handle deleted pseudo 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; 

view fiddle

the performance of view should reasonable provided there index on table1(id, dateofexam)


Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -