Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecutenonQuery not working

I have stored proc as below:

ALTER PROC pr_Update_Users_Nomination
(
      @UserID AS VARCHAR(100),  
      @Nominated AS BIT
)
AS

UPDATE User
SET isNominated = @Nominated
WHERE 
EMPID = @UserID;

I want to call this procedure from c# code: Below is the code I am trying:

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();
}

I get an error saying

Incorrect Syntax near @Nominated
like image 923
user1820973 Avatar asked Dec 09 '22 19:12

user1820973


2 Answers

first, when executing a procedure with parameter(s), separate the parameters with a comma

EXECUTE pr_Update @UserID, @Nominated

second, modify your code into this,

    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
            }

        }
    }
like image 123
John Woo Avatar answered Dec 11 '22 11:12

John Woo


You are missing a comma (,) between the parameters.

It should be

mySqlCom.CommandText = "EXECUTE pr_Update @UserID, @Nominated";
mySqlCom.Parameters.Add("@UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("@Nominated", SqlDbType.Bit).Value = Nominated;

Alternatively, since all you are doing is calling a stored proc, you could do:

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;
like image 23
SWeko Avatar answered Dec 11 '22 11:12

SWeko