簡體   English   中英

如何從表中刪除一行並將其通過SQL語句插入另一行?

[英]How can I remove one row from a table and insert it into another via a SQL statement?

沒有刪除語句,這是我的問題,我的SQL語句工作正常。 我使用2個OleDbCommands調用單獨的查詢。 這是我當前在C#中使用的SQL語句:

string mysql = "Insert Into Completed([Batch number], [Product], [Weight]) VALUES('" + batchNumber + "','" + product + "','" + weight + "')"; 

字符串newsql =“從干燥機中刪除[批次號] ='” + batchNumber +“'”;

這是我最近在代碼中失敗的嘗試:

        if (conn.State == ConnectionState.Open)
        {

            try
            {
                using (System.Transactions.TransactionScope tScope = new TransactionScope())
                {
                    string batchNumber = txtBatchNumber3.Text.ToString();
                    string product = txtProduct3.Text.ToString();
                    string weight = txtWeight3.Text.ToString();

                    string mysql = "Insert Into Packing([Batch number], [Product], [Weight]) VALUES('" + batchNumber + "','" + product + "','" + weight + "') ";
                    string newsql = "DELETE * FROM Dryers WHERE [Batch number]='" + batchNumber + "'";

                    OleDbCommand cmd = new OleDbCommand(mysql, conn);
                    cmd.ExecuteNonQuery();
                    OleDbCommand cmd2 = new OleDbCommand(newsql, conn);
                    cmd2.ExecuteNonQuery();

                    tScope.Complete();

                }


                MessageBox.Show("Data saved successfuly...!");
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed due to" + ex.Message);
            }
            finally
            {
                conn.Close();                    
            }
            }                
        else
        {
            MessageBox.Show("Connection Failed");
        }

    }
    }
}

VS2012出現以下錯誤:

由於條件表達式中的數據類型不匹配而失敗。

您無法在Access中執行此操作。 您必須調用兩個單獨的SQL字符串。

使用兩個語句,但是將它們包裝在一個事務中,因此它是一個工作單元。

BEGIN TRANSACTION
COMMIT

如果您想使用C#進行操作,則可以將查詢包裝在事務范圍中。

using (System.Transactions.TransactionScope tScope = new TransactionScope())
{
    //do work here
    //if work is completed
    tScope.Complete();

    //else do nothing the using statement will dispose the scope and rollback your changes.
}

這是Microsoft的演練,內容涉及如何針對訪問數據庫建立連接並使用ADO.NET查詢。 https://msdn.microsoft.com/en-us/library/ms971485.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM