2012-10-18 49 views
0

我一直在嘗試將參數添加到循環內的存儲過程。下面給出的是我聲明我的變量的代碼。C#:將參數添加到循環內的存儲過程

SqlConnection con = new SqlConnection(); 
     Connect conn = new Connect(); 
     SqlDataReader readerCourseID = null; 
     con = conn.getConnected(); 
     con.Open(); 
     SqlCommand cmdAssignCourse; 
     cmdAssignCourse = new SqlCommand("assignCourse", con); 
     cmdAssignCourse.CommandType = CommandType.StoredProcedure; 
     cmdAssignCourse.Parameters.Add("@sID", System.Data.SqlDbType.VarChar); 
     cmdAssignCourse.Parameters.Add("@cID", System.Data.SqlDbType.VarChar); 
     SqlParameter retValue = cmdAssignCourse.Parameters.Add("return", System.Data.SqlDbType.Int); 

而下面是我將值插入前面聲明的變量的代碼。

foreach (DataRow row in dt.Rows) 
      { 
       //get course id from course name. Pass row["Course Name"].ToString() 
       int i = getCourseID(row["Course Name"].ToString()); 



       //assignment of the course to student 
       cmdAssignCourse.Parameters["@sID"].Value = studentCurrID.Value.ToString(); 
       cmdAssignCourse.Parameters["@cID"].Value = i; 
       retValue.Direction = ParameterDirection.ReturnValue; 
       cmdAssignCourse.ExecuteNonQuery(); 
       if (retValue.Value.ToString() == "0") 
       { 
        MessageBox.Show("Added Course Successfully!"); 
        //return 0; 
       } 
       else 
       { 
        MessageBox.Show("An error occured! Possibly a duplication of data!"); 
        //return -1; 
       } 

      } 

但是,此代碼運行成功並顯示消息「已成功添加課程!」一旦。但在第一次成功運行後,每隔一次運行它就會給我「發生錯誤!可能是重複的數據!」信息。可能的錯誤不會清除變量。如何清除下面的變量。請幫我解決一下這個。謝謝!

+0

嘗試使用SqlServer的Profiler來看看你的代碼發送到數據庫是正確的。這會讓你知道你的參數值是否改變。 – RePierre

+0

你確定數據表dt中沒有重複條目嗎?爲什麼你將整數作爲varchars傳遞? – podiluska

回答

1

您沒有通過重新使用相同的SqlCommand和SqlConnection獲得任何東西。連接池將爲您完成所有艱苦的工作,無需重新發明輪子。這將是更清晰,更健壯分離出你的代碼,所以創建一個新的方法來執行的過程:

private int GenerateReturnValue(int courseID, int studentID) 
{ 
    using (var connection = new SqlConnection("Your Connection String")) 
    using (var command = new SqlCommand("assingCourse", connection) 
    { 
     connection.Open(); 
     command.CommandType = CommandType.StoredProcedure; 
     command.Parameters.Add("@sID", System.Data.SqlDbType.VarChar).Value = studentID.ToString(); 
     command.Parameters.Add("@cID", System.Data.SqlDbType.VarChar).Value = courseID.ToString(); 
     command.Parameters.Add("@Return", System.Data.SqlDbType.Int).Direction = ParameterDirection.ReturnValue; 
     command.ExecuteNonQuery(); 

     return (int)command.Parameters["@Return"].Value; 
    } 
} 

然後,只需調用該方法在循環。

foreach (DataRow row in dt.Rows) 
{ 
    int i = GenerateReturnValue(getCourseID(row["Course Name"].ToString()), studentCurrID.Value); 
    if (i = 0) 
    { 
     MessageBox.Show("Added Course Successfully!"); 
     //return 0; 
    } 
    else 
    { 
     MessageBox.Show("An error occured! Possibly a duplication of data!"); 
     //return -1; 
    } 
} 

另外我覺得James地說,問題在於這樣一個事實:you never re-pull the return value from the query, you are missing that line after execution: