0

Does anyone know how can I read the output variable from .net c#?

Example:

If I have the following stored proc which will return the output variables (@customer_id, @customer_name, @customer_address, @customer_age) instead of the select variable, how can I read the output variable with the following?

mySqlCommand.CommandText = "EXEC app_customers @name=" + sName.Text;
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
{
}
1

1 Answer 1

7

When the result is a single value (or if you're just interested in the first value in the first column), use the method ExecuteScalar.

It returns an object, simply cast it to the expected type.

int id = (int)mySqlCommand.ExecuteScalar();

Note: the way you're invoking a procedure is not the normal way to do it. Set the command to reference the stored procedure, then add appropriate parameters to the command.Parameters collection. Invoking the procedure using "exec ..." is not a best practice and may even leave you vulnerable. If you need more info on executing such a call, start here.

Edit:

If it is truly an output parameter you need to capture (I believe I misread your question), then the above paragraph is even more applicable. Consider this approach:

mySqlCommand.CommandText = "app_customers";
mySqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
mySqlCommand.Parameters.AddWithValue("@name", theValue);
var customerIdParam = mySqlCommand.Parameters.Add("@customer_id", System.Data.SqlDbType.Int);
customerIdParam.Direction = System.Data.ParameterDirection.Output;
// add more parameters, setting direction as appropriate

mySqlCommand.ExecuteNonQuery();
int customerId = (int)customerIdParam.Value;
// read additional outputs
Sign up to request clarification or add additional context in comments.

3 Comments

Parameters will also help protect you against SQL injection attacks.
@Anthony Pegram: how about if the output variable is more then one?
@Jin, you could try adding more parameters (should work with multiple output parameters, but I don't have experience trying that). However, if you are truly returning many such values, you might consider selecting those values and returning them as a table.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.