简体   繁体   English

使用SQL和C#从不同的表中删除行

[英]DELETE row from different tables using SQL and C#

I'm trying to delete several rows from tblOrderAA and one row from tblProInfo :(look at the picture) 我正在尝试从tblOrderAA中删除几行,并从tblProInfo中删除一行:(看图片) 在此处输入图片说明

Here is the code. 这是代码。 The error I get is: 我得到的错误是:

"the record has been deleted" “记录已被删除”

        private void DeleteFromDataBase()
        {
            string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
            OleDbConnection myConnection = new OleDbConnection(connectionString);
            string myDeleteQuery ="DELETE tblOrderAA.*, tblProInfo.*"+
" FROM tblProInfo INNER JOIN tblOrderAA ON tblProInfo.proInfoSerialNum = tblOrderAA.orderAASerialPro" +
" WHERE (((tblProInfo.proInfoScienceName)='"+comboBox1.SelectedItem.ToString()+"'))";

            OleDbCommand myCommand = new OleDbCommand(myDeleteQuery);
            myCommand.Connection = myConnection;
            try
            {
                myConnection.Open();
                myCommand.ExecuteNonQuery();
                myCommand.Connection.Close();

                MessageBox.Show("success");
            }
            catch (Exception e)
            {
                MessageBox.Show("error in : \n" + e.ToString());
            }

**NOTE:**When I use this code with SELECT instead DELETE it works. **注意:**当我将此代码与SELECT使用时, DELETE可以正常工作。

You cannot delete from multiple tables with one query that I know of. 我无法通过一个查询从多个表中删除。 If cascading deletes are on, then you can just delete from the Product table and the order records will automatically be deleted. 如果级联删除功能处于启用状态,则只需从“产品”表中删除,订单记录将自动删除。 If not, my recommendation would be to run the following queries in order to get the foreign key and delete from each table: 如果没有,我的建议是运行以下查询以获取外键并从每个表中删除:

"SELECT proInfoSerialNum "+
" FROM tblProInfo " +
" WHERE (((tblProInfo.proInfoScienceName)='"+comboBox1.SelectedItem.ToString()+"'))"

(store the result in a variable, say serialNum ) (将结果存储在一个变量中,例如serialNum

// delete the order records first so they are not orphaned
"DELETE tblOrderAA.* "+
" FROM tblOrderAA " +
" WHERE (((tblOrderAA.orderAASerialPro)='"+serialNum.ToString()+"'))"

// Delete the product info
"DELETE tblProInfo.*"+
" FROM tblProInfo " +
" WHERE (((tblProInfo.proInfoSerialNum )='"+serialNum.ToString()+"'))"

Note that I'm leaving out the actual C# code to run these queries, just giving you the SQL to give you an idea how I would do it. 请注意,我省略了实际的C#代码来运行这些查询,只是为您提供了SQL,以使您了解如何执行此操作。

I would guess that cascading deletes are possibly already turned on. 我想级联删除可能已经打开。 Delete only from the main table in your query or turn off the cascade in your database. 仅从查询的主表中删除,或关闭数据库中的级联。

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

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