C#SQL Row删除具有子行的父级

时间:2013-10-26 13:14:01

标签: c# sql sql-server datagridview sqldataadapter

我有一个程序,我将数据写入datagridviews,当我关闭表单数据时,保存到SQL Server数据库。但是当我有子行时删除父行时遇到问题。我收到并发冲突异常。当我检查数据库时,我看到仅删除子行。

以下是我创建SQL Server表的查询:

sql = "CREATE TABLE Auto("
                        + "VIN varchar(10) NOT NULL PRIMARY KEY,"
                        + "Make nvarchar(50),"
                        + "Model nvarchar(50),"
                        + "Year smallint);";

sql = "CREATE TABLE Repair("
                        + "ID int NOT NULL PRIMARY KEY,"
                        + "VIN varchar(10) NOT NULL,"
                        + "Description nvarchar(255),"
                        + "Cost float)"
                        + "ALTER TABLE Repair ADD FOREIGN KEY (VIN) REFERENCES Auto(VIN) ON DELETE CASCADE;";

我正在通过SqlDataAdapter更新数据库。

2 个答案:

答案 0 :(得分:0)

它对我有用,这里是小提琴

SQL fiddle

你有机会触发吗?

答案 1 :(得分:-1)

我不明白为什么你使用ALTER TABLE尝试这样的东西它对我来说很好:

CREATE TABLE Auto(
VIN varchar(10) NOT NULL PRIMARY KEY,
Make nvarchar(50),
Model nvarchar(50),
Year smallint
);

CREATE TABLE Repair(
ID int NOT NULL PRIMARY KEY,
VIN varchar(10) NOT NULL,
Description nvarchar(255),
Cost float,
FOREIGN KEY (VIN) REFERENCES Auto(VIN) ON DELETE CASCADE)
);

删除示例:

DELETE FROM Auto WHERE VIN = 'BMW';