I\'m trying to get output value from DB via ADO.NET. There\'s a client code:
using (var connection = new SqlConnection(ConnectionString))
{
Everyone's answer was about as clear as mud to me. Maybe this will help someone now that I found what worked.
Need to add size to the parameter
DynamicParameters Params = new DynamicParameters();
Params.Add("@ProfileID", ProfileID);
Params.Add("@CategoryName", CategoryName);
Params.Add("@Added", dbType: DbType.String, direction: ParameterDirection.Output,size:10);
db.Execute(sql, Params, commandType: CommandType.StoredProcedure, commandTimeout: 60);
var Added = Params.Get<string>("@Added");
Also, you can get the actual size of the parameters by inspecting the sproc with this little command:
SqlCommandBuilder.DeriveParameters(yourCommand)
and then just foreach your way through the parameters collection.
you have to set Size for parameter output
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("pDoSomethingParamsRes", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@i", 1);
var outParam = new SqlParameter("@out", SqlDbType.VarChar);
outParam.Direction = ParameterDirection.Output;
outParam.Size = 50; // this is example
command.Parameters.Add(outParam);
command.ExecuteNonQuery();
Console.WriteLine(command.Parameters["@out"].Value.ToString());
}
I had the same error and below is my code that works
cmd.Parameters("@ProjectKey").SqlDbType = SqlDbType.NVarChar
cmd.Parameters("@ProjectKey").Size = 150
cmd.Parameters("@ProjectKey").Direction = ParameterDirection.InputOutput
cmd.ExecuteNonQuery()
Parameter Size is required for variable size Output parameters. Generally ADO.NET decides the size of the parameter based on the Value assigned to the parameter (hence it is optional), but in output parameter since no value is Set, you need provide the size required for the parameter
Set the Parameter size to size of the output variable from the DB... Say 50
outParam.Size = 50;
I'm not sure if this is the same problem i've had before, but using a byte for a parameter can sometimes lead to this error.
Try this. Explicitly declare the i parameter as a variable. THEN assign it's value with the Value property.