2016-12-31 72 views
-5

我創建表單需要從存儲過程的訪問,當我跑我得到這個錯誤的應用程序:過程或函數「spAddEmployee」需要參數「@name」,但未提供

Procedure or function 'spAddEmployee' expects parameter '@name', which was not supplied

C#代碼:

string connectionstring = ConfigurationManager.ConnectionStrings["AddEmployee"].ConnectionString; 

using (SqlConnection con = new SqlConnection(connectionstring)) 
{ 
    SqlCommand cmd = new SqlCommand("dbo.spAddEmployee", con); 
    cmd.CommandType = CommandType.StoredProcedure; 

    con.Open(); 

    SqlParameter paramname = new SqlParameter(); 
    paramname.ParameterName = "@Name"; 
    paramname.Value = employee.Name; 
    cmd.Parameters.Add(paramname); 

    SqlParameter paramgender = new SqlParameter(); 
    paramname.ParameterName = "@gender"; 
    paramname.Value = employee.Gender; 
    cmd.Parameters.Add(paramgender); 

    SqlParameter paramcity = new SqlParameter(); 
    paramname.ParameterName = "@city"; 
    paramname.Value = employee.City; 
    cmd.Parameters.Add(paramcity); 

    SqlParameter paramdateofbirth = new SqlParameter(); 
    paramdateofbirth.ParameterName = "@dateofbirth"; 
    paramname.Value = employee.Dateofbirth; 
    cmd.Parameters.Add(paramdateofbirth); 

    cmd.ExecuteNonQuery(); 

    con.Close(); 
} 

my procedure code is given in snapshot

請幫我

回答

2

你一個重新使用您用於名稱爲性別和城市的相同SqlParameter對象(paramname)。所以它基本上是用第一個Gender和City來覆蓋這個值。所以我認爲你的City值是null,因此它會拋出一個錯誤。

這應該工作

using (var con = new SqlConnection(connectionstring)) 
{ 
    var cmd = new SqlCommand("dbo.spAddEmployee", con) { 
           CommandType = CommandType.StoredProcedure}; 
    con.Open(); 
    var paramname = new SqlParameter 
    { 
     ParameterName = "@Name", 
     Value = employee.Name 
    }; 
    cmd.Parameters.Add(paramname); 

    var paramgender = new SqlParameter 
    { 
     ParameterName = "@gender", 
     Value = employee.Gender 
    }; 
    cmd.Parameters.Add(paramgender); 

    var paramcity = new SqlParameter 
    { 
     ParameterName = "@city", 
     Value = employee.City 
    }; 
    cmd.Parameters.Add(paramcity); 

    var paramdateofbirth = new SqlParameter 
    { 
     ParameterName = "@dateofbirth", 
     Value = employee.Dateofbirth 
    }; 
    cmd.Parameters.Add(paramdateofbirth); 
    cmd.ExecuteNonQuery(); 

} 
+1

是感謝您的幫助,現在我可以訪問我的存儲過程 –

相關問題