简体   繁体   English

SQL服务器中的事务有Delete语句

[英]Transactions in SQL Server with Delete statement

This is my task: write a script that includes two SQL statements coded as a transaction to delete the row with a customer ID of 8 from the Customers table.这是我的任务:编写一个脚本,其中包含两个编码为事务的 SQL 语句,用于从Customers表中删除客户 ID 为 8 的行。 To do this, you must first delete all addresses for that customer from the Addresses table.为此,您必须首先从Addresses表中删除该客户的所有地址。

If these statements execute successfully, commit the changes.如果这些语句成功执行,则提交更改。 Otherwise, roll back the changes.否则,回滚更改。

My problem is that I am getting an error that looks like this:我的问题是我收到如下所示的错误:

Msg 547, Level 16, State 0, Line 9消息 547,16 级,State 0,第 9 行
The DELETE statement conflicted with the REFERENCE constraint "FK__Orders__Customer__35BCFE0A". DELETE 语句与 REFERENCE 约束“FK__Orders__Customer__35BCFE0A”冲突。 The conflict occurred in database "MyGuitarShop", table "dbo.Orders", column 'CustomerID'.冲突发生在数据库“MyGuitarShop”、表“dbo.Orders”、“CustomerID”列中。

My code:我的代码:

BEGIN TRAN;

DELETE FROM Addresses
WHERE CustomerID = 8;

DELETE FROM Customers
WHERE CustomerID = 8;

IF @@ROWCOUNT > 1
BEGIN
    ROLLBACK TRAN
    PRINT 'did not delete'
END
ELSE
BEGIN
    COMMIT TRAN;
END

Thank you!谢谢!

As long as Customers is referencing any Table on your Database then you can not delete it.只要客户引用数据库中的任何表,就不能删除它。 As per your REFERENCE constraint error message CustomerID = 8 have some order on table "dbo.Orders", column 'CustomerID' is referenced to Customers, so that`s why CustomerID=8 not deleting.根据您的 REFERENCE 约束错误消息 CustomerID = 8 在表“dbo.Orders”上有一些订单,列“CustomerID”被引用到客户,所以这就是 CustomerID = 8 不删除的原因。

First you need to delete order from dbo.Orders Table for CustormerID=8 or use首先,您需要从 dbo.Orders 表中删除 CustormerID=8 的订单或使用

ON DELETE CASCADE 

in the foreign key constraint definition.在外键约束定义中。

You're trying to delete a row when another row relies on it.当另一行依赖它时,您正试图删除一行。 This is what is known as referential integrity.这就是所谓的参照完整性。 It's there to prevent orphaned rows.它是为了防止孤立的行。

You'll need to delete any rows that relies on Customer ID 8 elsewhere.您需要删除在其他地方依赖客户 ID 8 的所有行。

In this immediate case, it is:-在这种直接情况下,它是:-

DELETE FROM Orders WHERE CustomerID = 8

But in your shoes, I'd probably comment as to why you're doing that, or even speak to whoever set you the task to ask if this is acceptable.但站在你的立场上,我可能会评论你为什么要这样做,或者甚至会与给你任务的人交谈,询问这是否可以接受。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM