SQL Server trigger delete or cascade delete

2019-09-07 22:20发布

问题:

First off I haven't done much SQL code before only the basic CRUD, but I'm involved in a project in which I have access to SQL Server and its up to me to write the SQL.

I've been busy looking on stackoverflow for a solution but (being new) it does not make any sense to me.

I'm using SQL Server 2012.

I have the following relationship (with foreign key constraints in place)

Client > Order > OrderItems

Order

Id
ClientId

OrderItems

Id
OrderId

I'm using EF and when I call my delete method on client I need to delete all the the related items in orders and orderitems tables

I need to add a trigger to go and delete orders and orderitems, but I'm not sure how to do this or if a cascade delete (I've heard of) is best?

Anyone have a quick example and advice of how to do this?

回答1:

For simple situations, use the cascade delete.

If you have more complex requirements, use the triggers, or a stored procedure for your deletions

http://msdn.microsoft.com/en-us/library/aa902684(v=sql.80).aspx