触发插入到同一个表中
我的数据库中有许多相互关联的表。 我有一个表(表一),其中插入了数据并且 id 自动递增。 一旦该行有一个 ID,我想将其插入到一个表(表三)中,其中包含来自表单的另一组 ID(此数据也将进入表中,因此可以来自该表),相同表单作为进入第一个表的数据的来源。
这两个 ID 一起构成第三个表的主键。
我该如何做到这一点,它表明多个 ID 与单个 ID 相连以用于其他目的。
谢谢。
I have many tables in my database which are interrelated. I have a table (table one) which has had data inserted and the id auto increments. Once that row has an ID i want to insert this into a table (table three) with another set of ID's which comes from a form(this data will also be going into a table, so it could from from that table), the same form as the data which went into the first table came from.
The two ID's together make the primary key of the third table.
How can I do this, its to show that more than one ID is joined to a single ID for something else.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您可能可以执行您所描述的操作(只需在表 1 触发器中将 INSERT 写入表 3),但您必须将表 3 行的附加信息放入表 1 行中,这不是'非常聪明。
我不明白为什么你会这样做,而不是在代码中编写 INSERT,这样阅读它的人就可以看到发生了什么。
触发器的问题在于它们很容易将业务逻辑隐藏在数据库中。 我认为(我相信我是这里的大多数人),如果所有业务规则都存在于同一个通用区域中,则更容易理解、管理、维护和全面处理应用程序。
使用触发器(例如,用于传播非规范化值)是有原因的,就像使用存储过程也是有原因的一样。 我要断言它们很大程度上与性能关键领域相关。 或者应该是。
I think you can probably do what you're describing (just write the INSERTs to table 3) in the table 1 trigger) but you'll have to put the additional info for the table 3 rows into your table 1 row, which isn't very smart.
I can't see why you would do that instead of writing the INSERTs in your code, where someone reading it can see what's happening.
The trouble with triggers is that they make it easy to hide business logic in the database. I think (and I believe I'm in the majority here) that it's easier to understand, manage, maintain and generally all-round deal with an application where all the business rules exist in the same general area.
There are reasons to use triggers (for propagating denormalised values, for example) just as there are reasons for useing stored procedures. I'm going to assert that they are largely related to performance-critical areas. Or should be.
您无法通过触发器执行此操作,因为触发器只能使用您已插入的数据,而不是当前仅驻留在用户界面中的数据。
通常,处理这种情况的方法是编写一个存储过程来插入会议,返回 id 值(在 SQL Server 中使用scope_identity(),但我确信其他数据库也有方法返回自动生成的 id) )。 然后,您可以使用该值将包含该表所需的其他值插入到另一个表中。 您当然希望将整个事情包装在一个事务中。
You can't do that through a trigger as the trigger only has available to it the data that you already inserted not data that is currenlty only residing in your user interface.
Normally how you handle this situation is that you write a stored proc that inserts the meeting, returns the id value (using scope_identity() in SQL Server, but I'm sure other databases would have method to return the auto-generated id as well). Then you would use that value to insert to the other table with the other values you need for that table. You would of course want to wrap the whole thing in a transaction.