4

我存储的过程如下:

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

4 回答 4

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
            }

        }
    }
于 2012-11-14T15:02:54.133 回答
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;
于 2012-11-14T15:02:44.503 回答
4

只给出存储过程的名称,因为您在之后的语句中添加参数。还要设置 CommandType。

 mySqlCom.CommandText = "pr_Update";
 mySqlCom.CommandType = CommandType.StoredProcedure;
于 2012-11-14T15:03:01.383 回答
1

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

mySqlCom.CommandText = "pr_Update";

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

mySqlCom.CommandType = CommandType.StoredProcedure;

有关更多信息,请参阅MSDN 页面

于 2012-11-14T15:06:16.963 回答