簡體   English   中英

如何使用 ADO.NET 將多行插入 SQL 服務器?

[英]How can I insert multiple rows into SQL Server using ADO.NET?

我想為同一個查詢輸入不同的條目,但是我遇到了錯誤的小時數和日期:

參數必須是唯一的

有什么辦法嗎?

List<int> hoursList = new List<int>{1,2,3,4,5,6,7};

string connectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;

using (var con = new SqlConnection(connectionString))
{
    var query = @"INSERT INTO EmployeeTable (EmployeeID, ProjectID, CategoryID, SubCategoryID, Location, Date, Hours)
                  VALUES (@EmployeeID, @ProjectID, @CategoryID, @SubCategoryID, @Location, @Date, @Hours,)";

    using(var cmd = new SqlCommand(query,con))
    {
        cmd.Parameters.AddWithValue("@EmployeeID",obj.EmployeeID);
        cmd.Parameters.AddWithValue("@ProjectID", obj.ProjectID);
        cmd.Parameters.AddWithValue("@CategoryID", obj.CategoryID);
        cmd.Parameters.AddWithValue("@SubCategoryID", obj.SubCategoryID);
        cmd.Parameters.AddWithValue("@Location", obj.Location);

        for(int j = 0; j < hoursList.Count; j++)
        {
            cmd.Parameters.AddWithValue("@Hours", hoursList[j]);
            cmd.Parameters.AddWithValue("@Date", DateTime.Now.AddDays(j).ToString("yyyy/MM/dd"));

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

您不能在循環中調用.AddParameter - 這將不斷嘗試一遍又一遍地添加相同的參數(相同的名稱),這會導致您看到的問題。

將參數的聲明放在循環之外- 在循環內只設置值 - 如下所示:

// define the parameters **ONCE**, outside the loop
cmd.Parameters.Add("@Hours", SqlDbType.Int);
cmd.Parameters.Add("@Date", SqlDbType.DateTime);

for (int j = 0; j < hoursList.Count; j++)
{
    // inside the loop, just set the **values** - not define the same
    // parameters over and over again .....
    cmd.Parameters["@Hours"].Value = hoursList[j];
    cmd.Parameters["@Date"].Value = DateTime.Now.AddDays(j);

    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}

另外 - 因為@Date很明顯是一個日期- 你應該這樣對待它並將它作為DateTime值傳遞給查詢 - 不要在沒有真正需要的情況下將所有內容轉換為字符串!

總體而言:這將創建多行 - 但大多數列一遍又一遍地相同。 這聞起來像是一個糟糕的數據庫設計 - 我會檢查日期和時間是否不應該分開到他們自己的表中,這樣你就可以在EmployeeTable中有一個條目,第二個表包含 0-n 個條目對於該員工,只有日期和時間。

暫無
暫無

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

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