在一个查询中删除然后插入?

时间:2018-11-02 03:03:40

标签: c# asp.net .net oledb sql-server-ce

有没有一种方法可以删除旧记录,然后插入新记录?我有一个Excel电子表格,正在使用OLEDB,然后将其传递给SQL Server CE命令以插入到.sdf数据库文件中。

我要删除旧记录或更新旧记录(好得多),然后插入新记录。

我在电子表格EmployeeLeaveHistory中有数据,其中包含列Emp_NumEmp_Name

Emp_Num | Emp_Name |
--------+----------+
12345   | anna     |
12345   | anna     |
23451   | jonalyn  |

通过使用oledb,它将获得记录

        int EmployeeNum;
        string EmployeeName;
        string constr = "";
        string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
        string path = Server.MapPath("~/Excel/" + FileUpload1.FileName);
        FileUpload1.SaveAs(path);

        if (ext.Trim() == ".xls")
        {
            constr = "Povider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";Extended Properties=\"Excel.8.0;HDR=Yes;IMEX=2\"";
        }
        else if (ext.Trim() == ".xlsx")
        {
            constr = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
        }

        string query = "SELECT * FROM [EmployeeLeaveHistory$]";

        using (OleDbConnection conn = new OleDbConnection(constr))
        {
            conn.Open();

            using (OleDbCommand cmd2 = new OleDbCommand(query, conn))
            {
                using (OleDbDataReader dr2 = cmd2.ExecuteReader())
                {
                    while (dr2.Read())
                    {
                        EmployeeNum = Convert.ToInt32(dr2["Emp_Num"]);
                        EmployeeName = Convert.ToString(dr2["Emp_Name"]);

                        SaveLeave(EmployeeNum, EmployeeName);
                    }
                }
            }
        }
    }

然后我有一个私人的void SaveLeave,他将从oledb中捕获记录,然后将其插入到我的.sdf文件中。

private void SaveLeave(Int32 EmployeeNum, string EmployeeName)
{
        string constring = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
       string check = "SELECT COUNT(*) FROM EMPLOYEELEAVEHISTORY WHERE Id=@@IDENTITY";
       string update = "UPDATE EMPLOYEELEAVEHISTORY SET EmployeeName=@EmployeeName WHERE EmployeeNum=@EmployeeNum;";
       string insert = "INSERT INTO EMPLOYEELEAVEHISTORY(EmployeeNum, EmployeeName) VALUES (@EmployeeNum, @EmployeeName);";

        using (SqlCeConnection con = new SqlCeConnection(constring))
        {
            con.Open();

            using (SqlCeCommand cmd = new SqlCeCommand(check, con))
            {
                cmd.Parameters.AddWithValue("@EmployeeNum", EmployeeNum);

                using (SqlCeDataReader read = cmd.ExecuteReader())
                {
                    read.Read();

                    int count = read.GetInt32(0);

                    if (count > 0)
                    {

                        using (SqlCeCommand upt = new SqlCeCommand(update))
                        {
                            upt.Parameters.AddWithValue("@EmployeeNum", EmployeeNum);
                            upt.Parameters.AddWithValue("@NoOfDays", NoOfDays);
                            upt.Connection = con;
                            upt.ExecuteNonQuery();
                        }
                    }
                    else
                    {                            using (SqlCeCommand inst = new SqlCeCommand(insert))
                        {
                            inst.Parameters.AddWithValue("@EmployeeNum", EmployeeNum);
                            inst.Parameters.AddWithValue("@EmployeeName", EmployeeName);
                            inst.Connection = con;
                            inst.ExecuteNonQuery();
                        }
                    }
                }                
            }          
        }
    }

如果我使用Delete语句,则Excel记录的最后一行23451|jonalyn|是唯一插入到sdf中的记录。现在我正在使用更新语句,但是问题是当我使用更新语句时,记录没有更新,但是它复制了记录,如果我在excel中添加了另一条记录,像这样:

Emp_Num | Emp_Name |
--------+----------+
12345   | anna     |
12345   | anna     |
23451   | jonalyn  |
12      | jade     |

然后对我的.sdf使用插入查询,我的.sdf中的记录将如下所示:

EmployeeNum | EmployeeName |
------------+--------------+
12345       | anna         |
12345       | anna         |
23451       | jonalyn      |
12345       | anna         |
12345       | anna         |
23451       | jonalyn      |
12          | jade         |

有人可以帮助我吗?谢谢

1 个答案:

答案 0 :(得分:0)

我尝试了不同的方式来执行更新语句,但是具有相同EmployeeNum的每个记录都将由OLEDBcommand获取的最后一条记录进行更新。对我而言,最好的方法是删除记录并插入新记录(请注意,这里唯一的问题是,如果您将旧记录删除到excel文件中,则除非将旧记录保存到另一个excel文件中,否则无法检索)。

这是DELETE语句的代码,然后是INSERT。

            string query2 = "SELECT * FROM [EmployeeLeaveHistory$]";
            using (OleDbCommand cmd2 = new OleDbCommand(query2, conn))
            {
              using (OleDbDataReader dr2 = cmd2.ExecuteReader())
                {

                    string constring = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
                    using (SqlCeConnection con = new SqlCeConnection(constring))
                    {
                        con.Open();
                        string del = "DELETE FROM EMPLOYEELEAVEHISTORY";
                        using (SqlCeCommand delete = new SqlCeCommand(del))
                        {
                            delete.Connection = con;
                            delete.ExecuteNonQuery();
                        }


                        using (SqlCeBulkCopy copy = new SqlCeBulkCopy(con))
                        {
                            copy.DestinationTableName = "EMPLOYEELEAVEHISTORY";

                            copy.ColumnMappings.Add("Emp_Num", "EmployeeNum");
                            copy.ColumnMappings.Add("Emp_Name", "EmployeeName");


                            copy.WriteToServer(dr2);


                        }
                    }
                }
            }