SQL Server 触发器、存储过程
我从未使用过触发器或存储过程。现在我想研究如何以及何时使用它。 我有名为 Products 的表,当产品表填充行时,我想将 ProductID 和 UnitsInStock 复制到 Inventory 表中。库存表中存在一个问题,即在填充行时必须填充购买用户的列。触发器或存储过程对于这种情况有用吗?
I dont ever used triggers or stored procedures. Now i want to study how and when i use that.
I have table named Products, when products table filling with row i want to copy ProductID and UnitsInStock and paset into Inventory table. There is one problem in inventory table is column which must fill buy user when row is filling. Would triggers or stored procedures will be useful for this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我个人在使用代码时永远不会使用触发器,如果所有工作都在 sql 中完成就可以了。原因是,首先其他人很难意识到这是一个在后端工作的触发器。其次,如果您的代码中有错误……触发器是您检查的最后一件事。如果列名发生变化,很容易发现代码中的错误。存储过程很好,但这一切都取决于组织。我已经开始在代码中执行 sql,并且喜欢它,因为无需来回查找相关存储过程的数百个存储过程。不过我的看法...
i personally would never use triggers when i'm using code it is fine if all your work is being done in sql. The reason is that it is firstly difficult for someone else to realise that it is a trigger doing work in the back-end. Secoundly if there is an error in your code ... triggers are the last thing you check. And if column names change it is easy to pick up the error in code. Stored procedures are good, but it all depends from organisation to organisation. I have gotten into doing sql in code and like it as there is no back and forth work at looking through hundreds of stored procedures for the relevant one. My views though ...
如果您只需在插入或更新后将内容从一个表复制到另一个表,那么触发器是执行此操作的正确方法。
但是,如果在您的情况下,一列必须填充用户应用的数据,您可能必须从代码中执行此操作。
关于存储过程的使用:看看这个。但网络上有很多关于这个主题的讨论。只需谷歌一下即可。
If you just need to copy stuff from one table to another after inserting or updating, a trigger is the right way to do this.
But if in your case a column must be filled with user-applied data, you probably will have to do this from your code.
About the use of stored procedures: take a look at this. But there are many discussions on the web about this theme. Just google a bit around.
使用存储过程,传入所需的所有值作为参数,然后在事务中将更改发布到产品表,然后发布到库存表,然后立即将更改提交到两个表 - 这样两个表都会更新,或者也没有。
Use a stored procedure, pass in all the values that are needed as parameters, then within a transaction post changes to the products table and then the inventory table and then commit your changes to both tables at once - so either both tables get updated, or neither does.