ExecutenonQuery无效

时间:2012-11-14 15:01:06

标签: c# sql sql-server-2008 executenonquery

我已将proc存储如下:

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

4 个答案:

答案 0 :(得分:5)

首先,当使用参数( s )执行过程时,用逗号分隔参数

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
            }

        }
    }

答案 1 :(得分:4)

参数之间缺少逗号(,)。

应该是

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;

答案 2 :(得分:4)

仅提供存储过程的名称,因为您在此后的语句中添加参数。同时设置CommandType。

 mySqlCom.CommandText = "pr_Update";
 mySqlCom.CommandType = CommandType.StoredProcedure;

答案 3 :(得分:1)

您正在调用错误的SQL。您应该将命令的命令文本设置为pr_Update

mySqlCom.CommandText = "pr_Update";

并将类型命令类型设置为存储过程:

mySqlCom.CommandType = CommandType.StoredProcedure;

有关详情,请参阅MSDN page