如何在C#中使用存储过程返回结果列表?

时间:2015-08-11 04:56:00

标签: c# sql-server asp.net-mvc stored-procedures sqlcommand

这是我的存储过程:

    CREATE  Proc UpdateChecklist
(
    @TemplateId As INT
) as
begin
    select MF.CheckListDataId from TemplateModuleMap TM
    inner join ModuleField MF 
    on TM.ModuleId = MF.ModuleId
    where TM.TemplateId = @TemplateId and MF.CheckListDataId not in
    (select cktm.CheckListDataId from ChecklistTemplateMap cktm
    inner join ChecklistData ckd
    on cktm.CheckListDataId = ckd.Id
    where cktm.TemplateId = @TemplateId)
end

所以我希望这里有一个CheckListDataId的返回列表。我正在尝试使用Database.ExecuteSqlCommand()但尚未成功。如何在此处返回CheckListDataId列表?我需要修改我的存储过程吗?我是sql的新手。

有什么建议吗?这是一个ASP.NET MVC 5项目

1 个答案:

答案 0 :(得分:5)

您的存储过程会返回结果集,您可以在C#中按需处理。

我会以这种方式从我的模型类中调用该过程:

DataTable loadLogFilterData = SQLHelper.ExecuteProc(STORED_PROCEDURE_NAME, new object[] { 
    //Parameters to Stored Proc If Any
                });

然后我有一个SQLHelper类,我在其中创建SQL Connection并使用委托方法来调用存储过程。

public static DataTable ExecuteProc(string procedureName, Object[] parameterList, string SQLConnectionString) // throws SystemException
        {
            DataTable outputDataTable;

            using (SqlConnection sqlConnection = OpenSQLConnection(SQLConnectionString))
            {
                using (SqlCommand sqlCommand = new SqlCommand(procedureName, sqlConnection))
                {
                    sqlCommand.CommandType = CommandType.StoredProcedure;

                    if (parameterList != null)
                    {
                        for (int i = 0; i < parameterList.Length; i = i + 2)
                        {
                            string parameterName = parameterList[i].ToString();
                            object parameterValue = parameterList[i + 1];

                            sqlCommand.Parameters.Add(new SqlParameter(parameterName, parameterValue));
                        }
                    }

                    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
                    DataSet outputDataSet = new DataSet();
                    try
                    {
                        sqlDataAdapter.Fill(outputDataSet, "resultset");
                    }
                    catch (SystemException systemException)
                    {
                        // The source table is invalid.
                        throw systemException; // to be handled as appropriate by calling function
                    }

                    outputDataTable = outputDataSet.Tables["resultset"];
                }
            }

            return outputDataTable;
        }

您将存储过程的每个输出都视为结果集,无论它包含什么。然后,您需要在模型中操作该结果集以填充所需的数据结构和数据类型。