简体   繁体   中英

MSSQL Delete query on a table with foreign key

I have 2 tables

t1 - Categories Id Name

t2 - Products Id Name 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.)

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

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.

This is expected functionality. You can amend SQL Server to use cascading deletes, so all connected records are also deleted, but use this carefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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