0

i am inserting some values in my table and at the same time, i want to call stored procedure that does some updates but i am having some issues with the syntax. I have searched online but could not find anything. I am just trying to figure out how can to use the same connection. here is my code:

sqlcmd.CommandText = "INSERT INTO MyTable(ID, Name ) VALUES(@ID, @Name)";
sqlcmd.Parameters.Clear();
sqlcmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ID;
sqlcmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = Name;

sqlcmd.Connection = sqlcon;


sqlcmd.ExecuteNonQuery();

i saw some example on the internet but was not able to figure out how to use the same connection. here is the example i found:

SqlCommand myCMD = new SqlCommand("sp_Test", sqlcon);
myCMD.CommandType = CommandType.StoredProcedure;
2

1 Answer 1

4

Code for executing procedure is like as follows

using( SqlConnection con = new SqlConnection(connenctionstring))
{
 using(SqlCommand myCMD = new SqlCommand("sp_Test", con))
 {
  myCMD.CommandType = CommandType.StoredProcedure;
  con.Open();
  myCMD.ExecuteNonQuery();//as its insert command
  con.Close();
 }
}

Must use Using which dispose as well as close connection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.