SoFunction
Updated on 2025-03-01

How to execute stored procedure methods in C#


public class DataHelper
    {
        private string connString = null;
        public DataHelper(string conStr)
        {
            = conStr;
        }
        /// <summary>
//// Execute stored procedures
        /// </summary>
/// <param name="ep">Properties for executing stored procedures
/// The name of the ProcName stored procedure
/// MethodName The name of the SqlCommand method
/// Parameters of PrmList stored procedure
        /// </param>
/// <returns>Return the result of execution</returns>
        public object ExecProcRetObj(ExeProc ep)
        {
            if ( != null && != )
            {
                try
                {
                    SqlConnection con = new SqlConnection();
                    SqlCommand cmd = new SqlCommand();
                    = con;
                    = "Exec " + + " ";
                    foreach (object obj in )
                    {
                        += obj + ",";
                    }
                    = ( - 1, 1);
                    Type ty = ();
                    ();

//Use reflection to execute the corresponding method according to the input method name

                    object retObj = (, , null, cmd, null);
                    if (().FullName == "")
                    {
//Convert the returned object to DataTable
                        DataTable retDt = new DataTable();
                        (retObj as SqlDataReader);
                        ();
                        ();
                        return retDt;
                    }

                    return retObj;
                }
                catch (Exception ex)
                {
("Error occurred when obtaining data\n" + );
                }

            }
            return null;
        }
    }