Update one to many relationship data in database
I want to update a list in the database which has one to many relationship.
For example, There are over 100 subjects and a student can select whatever he wants. Let's say next time that student edit his selection.
What is the way you would update the database for this case? What I am used to doing is delete all the past selections and add all the newly selected 开发者_JS百科subjects. This is pretty easy logic but I am just wondering whether there is a better way to do this in terms of performance. In my case 'delete' is a single database call and inserting all is a loop in a single database connection.
I understand we can add a logic to identify the deleted records and newly added records. Is it realy worth to do that? What you would do for similar cases?
Thanks!
For brevity and simplicity, there is nothing really wrong with a delete-reinsert approach, barring foreign key hooks from child tables or triggers firing for each (re)insert.
Another way to do it could be to pass the new set as a table-valued parameter to a SP to Sql Server, which would then use a duo of queries to make the change
delete many_table
where studentid=@studentid and someid not in (select someid from @tableparam p)
insert many_table(studentid, someid)
select @studentid, p.someid
from @tableparam p left join many_table t on p.someid=t.someid and t.studentid=@studentid
where t.someid is null
(there is a more elegant MERGE syntax for SQL Server 2008, which is yet another option, further testing your TSQL skills)
精彩评论