ExecutenonQuery无效
我存储过程如下:
ALTER PROC pr_Update_Users_Nomination ( @UserID AS VARCHAR(100), @Nominated AS BIT ) AS UPDATE User SET isNominated = @Nominated WHERE EMPID = @UserID;
我想从c#代码调用这个过程:下面是我正在尝试的代码:
void OpenConnection() { string Nominated = "False"; //Connection String string sConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString; SqlConnection mySqlCon = new SqlConnection(sConnString); SqlCommand mySqlCom = mySqlCon.CreateCommand(); //Call the stored proc and provide in parameters mySqlCom.CommandText = "EXECUTE pr_Update @UserID @Nominated"; mySqlCom.Parameters.Add("@UserID", SqlDbType.VarChar, 20).Value = UserID; mySqlCom.Parameters.Add("@Nominated", SqlDbType.Bit).Value = Nominated; mySqlCon.Open(); mySqlCom.ExecuteNonQuery(); mySqlCon.Close(); }
我说错了
Incorrect Syntax near @Nominated
首先,当使用参数执行过程时,用逗号分隔参数
EXECUTE pr_Update @UserID, @Nominated
第二,修改你的代码,
string sConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString; using(SqlConnection mySqlCon = new SqlConnection(sConnString)) { using(SqlCommand mySqlCom = new SqlCommand()) { mySqlCom.Connection = mySqlCon; mySqlCom.CommandText = "pr_Update"; mySqlCom.CommandType = CommandType.StoredProcedure; mySqlCom.Parameters.Add("@UserID", SqlDbType.VarChar, 20).Value = UserID; mySqlCom.Parameters.Add("@Nominated", SqlDbType.Bit).Value = Nominated; try { mySqlCon.Open(); mySqlCom.ExecuteNonQuery(); } catch(SqlException ex) { // do something with the exception // don't hide it } } }
您缺少参数之间的逗号(,)。
它应该是
mySqlCom.CommandText = "EXECUTE pr_Update @UserID, @Nominated"; mySqlCom.Parameters.Add("@UserID", SqlDbType.VarChar, 20).Value = UserID; mySqlCom.Parameters.Add("@Nominated", SqlDbType.Bit).Value = Nominated;
或者,因为你所做的只是调用存储过程,你可以这样做:
mySqlCom.CommandType = CommandType.StoredProcedure ; mySqlCom.CommandText = "pr_Update"; //no need to specify parameter names mySqlCom.Parameters.Add("@UserID", SqlDbType.VarChar, 20).Value = UserID; mySqlCom.Parameters.Add("@Nominated", SqlDbType.Bit).Value = Nominated;
仅提供存储过程的名称,因为您在此后的语句中添加参数。 还设置CommandType。
mySqlCom.CommandText = "pr_Update"; mySqlCom.CommandType = CommandType.StoredProcedure;
你正在调用错误的SQL。 您应该将命令的命令文本设置为仅pr_Update
:
mySqlCom.CommandText = "pr_Update";
并将类型命令类型设置为存储过程:
mySqlCom.CommandType = CommandType.StoredProcedure;
有关更多信息,请参阅MSDN页面