Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Stored Procedure With Nameless Parameters

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;
}
like image 553
johnny 5 Avatar asked Jan 29 '26 21:01

johnny 5


1 Answers

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

like image 78
Remus Rusanu Avatar answered Feb 01 '26 09:02

Remus Rusanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!