I was just wondering if there is a way to execute a stored procedure with out naming the parameters. Meaning that C# resolves the parameters in the order they're declared within the stored procedure.
public static DataTable GetRelatedResources(string StoredProcedure, object[] Parameters)
{
var Results = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection())
{
using (SqlCommand cmd = new SqlCommand(ConfigurationManager.ConnectionStrings["MK3Entities"].ConnectionString))
{
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = StoredProcedure;
if (Parameters!= null)
{
foreach(var Param in Parameters)
{
// I Want To Do something like this
cmd.Parameters.AddWithValue(Param);
}
}
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(Results);
}
}
}
catch (Exception ex)
{
MMSLogger.Instance.WriteToLog("Exception Executing Stored Procedure:" + ex.Message);
}
return Results;
}
Execute a command instead, and pass in parameters '@p1', '@p2' etc:
cmd.CommandType = CommandType.Text;
cmd.CommandText = 'exec ' + StoredProcedure;
int i=0;
string comma = ' ';
foreach(var Param in Parameters)
{
var paramName = String.Format("@P{0}", i);
cmd.CommandText += comma + paramName;
cmd.Parameters.AddWithValue(paramName, Param);
++i;
comma = ', ';
}
Be aware that AddwithValue is huge performance antipattern. See How Data Access Code Affects Database Performance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With