How can I retrieve a list of parameters from a stored procedure in SQL Server

后端 未结 8 1107
慢半拍i
慢半拍i 2020-11-28 12:14

Using C# and System.Data.SqlClient, is there a way to retrieve a list of parameters that belong to a stored procedure on a SQL Server before I actually execute it?

I

8条回答
  •  攒了一身酷
    2020-11-28 12:40

    Although its not exactly what you want, here's some sample code that uses the SqlConnection.GetSchema() method to return all the stored procedures associated with a database, and then subsequently all the parameter names and types for each stored procedure. The example below just loads this into variables. Note that this also returns all the "system" stored procedures, which might not be desirable.

    Steve

        public void LoadProcedureInfo()
        {
            SqlConnection connection = new SqlConnection();
    
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["ConnectionString"];
    
            connection.ConnectionString = settings.ConnectionString;
            connection.Open();
    
            DataTable procedureDataTable = connection.GetSchema("Procedures");
            DataColumn procedureDataColumn = procedureDataTable.Columns["ROUTINE_NAME"];
    
            if (procedureDataColumn != null)
            {
                foreach (DataRow row in procedureDataTable.Rows)
                {
                    String procedureName = row[procedureDataColumn].ToString();
    
                    DataTable parmsDataTable = connection.GetSchema("ProcedureParameters", new string[] { null, null, procedureName });
    
                    DataColumn parmNameDataColumn = parmsDataTable.Columns["PARAMETER_NAME"];
                    DataColumn parmTypeDataColumn = parmsDataTable.Columns["DATA_TYPE"];
    
                    foreach (DataRow parmRow in parmsDataTable.Rows)
                    {
                        string parmName = parmRow[parmNameDataColumn].ToString();
                        string parmType = parmRow[parmTypeDataColumn].ToString();
                    }
                }
            }
        }
    

提交回复
热议问题