问题描述:

I have a stored procedure that I call like this:

string proc = "SpCreate '00111', 3";

using (SqlCommand command = new SqlCommand(proc, conn))

{

command.CommandType = CommandType.Text;

command.CommandTimeout = 1000;

string returnCode = command.ExecuteScalar().ToString();

}

The above gode works fine. But once I add in a parameter, I get the incorrect syntax near 'SpCreate'. What gives? (Code below causes error.)

string proc = "SpCreate '00111', @myId";

using (SqlCommand command = new SqlCommand(proc, conn))

{

SqlParameter paramName = new SqlParameter("@myId", SqlDbType.Int) { Value = 3 };

command.Parameters.Add(paramName);

command.CommandType = CommandType.Text;

command.CommandTimeout = 1000;

string returnCode = command.ExecuteScalar().ToString();

}

网友答案:

Edited my answer after looking at some of my own code and realizing I had some errors.

You need to set the CommandType to StoredProcedure.

Edit: Example Source Code added

 string proc = "SpCreate";

 using (SqlCommand command = new SqlCommand(proc, conn))
 {
       SqlParameter paramName = new SqlParameter("@myId", SqlDbType.Int);
       paramName.Value = 3;
       command.Parameters.Add(paramName);

       command.CommandType = CommandType.StoredProcedure;
       command.CommandTimeout = 1000;

       string returnCode = command.ExecuteScalar().ToString();
 }
相关阅读:
Top