更新数据库中的一对多关系数据
我想更新数据库中具有一对多关系的列表。
例如,有超过100个科目,学生可以选择任何他想要的科目。假设下次该学生编辑他的选择。
对于这种情况,您将如何更新数据库?我习惯做的是删除所有过去的选择并添加所有新选择的主题。这是非常简单的逻辑,但我只是想知道在性能方面是否有更好的方法来做到这一点。在我的例子中,“删除”是单个数据库调用,而插入全部是单个数据库连接中的循环。
我知道我们可以添加一个逻辑来识别已删除的记录和新添加的记录。真的值得这样做吗?对于类似的情况你会怎么做?
谢谢!
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 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了简洁起见,删除重新插入方法并没有什么问题,禁止子表中的外键挂钩或每次(重新)插入时触发触发器。
另一种方法是将新集作为表值参数传递给 Sql Server 的 SP,然后 SP 将使用一组查询来进行更改
(SQL Server 2008 有一种更优雅的 MERGE 语法,这是另一个选项,进一步测试您的 TSQL 技能)
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
(there is a more elegant MERGE syntax for SQL Server 2008, which is yet another option, further testing your TSQL skills)