简体   繁体   English

MSSQL删除具有外键的表上的查询

[英]MSSQL Delete query on a table with foreign key

I have 2 tables 我有2张桌子

t1 - Categories Id Name t1-类别ID名称

t2 - Products Id Name CategoryId t2-产品ID名称CategoryId

I have a foreign key and it`s working but when I want to run a Delete query (for example O keep getting an error because of the foreign key.) 我有一个外键,它可以正常工作,但是当我想运行Delete查询时(例如,由于外键,O会不断出错)。

ths is my code: 这是我的代码:

        protected void dlCategory_DeleteCommand(object source, DataListCommandEventArgs e)
{
    string Id = ((Label)e.Item.FindControl("Label1")).Text;
    string SQL = "DELETE FROM Categories WHERE PrimaryKey=@ID;";
    SqlCommand cmd = new SqlCommand(SQL, conn);
    cmd.Parameters.AddWithValue("@ID", Id);

    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();

    BindDL();
}

If I remove the foreign key it`s working just fine! 如果我删除外键,它就可以正常工作!

As far as I'm aware you can't run a query with the Primary Key as a parameter, You need to do the long handed way. 据我所知,您不能使用主键作为参数来运行查询,您需要做很多事情。

string SQL = "DELETE FROM Categories WHERE PrimaryKey= '$Cat_ID';";

Similar answer here Mysql Select record where PRIMARY key = x 这里类似的答案Mysql选择记录,其中PRIMARY键= x

It looks like you are trying to remove a record from Categories, but that record cannot be deleted because it is in use by the Products table. 您似乎正在尝试从“类别”中删除一条记录,但是由于“产品”表正在使用该记录,因此无法删除该记录。

If you have a category of 'clothes' and a product of 't-shirt' that is given the category of clothes, then removing the category would give you a data error, as the database is now inconsistent. 如果您拥有“衣服”的类别,并且给定了“衣服”类别的“ T恤”产品,那么删除该类别将给您数据错误,因为数据库现在不一致。

This is expected functionality. 这是预期的功能。 You can amend SQL Server to use cascading deletes, so all connected records are also deleted, but use this carefully. 您可以修改SQL Server以使用级联删除,因此也删除了所有连接的记录,但请谨慎使用。

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

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