【问题标题】:Generic Execution of Stored Procedure in CSharp [closed]CSharp中存储过程的通用执行[关闭]
【发布时间】:2014-08-04 14:27:24
【问题描述】:

我正在创建一个通用库来执行存储过程。不同的存储过程可以有不同数量的输入参数。

返回类型始终是一个表格。

使用 ADO.NET 或 Dapper,我可以执行带参数的 SP,但如何使其通用以执行任何接受输入参数并返回表结果的 SP。

谢谢

【问题讨论】:

  • 创建一个接收字符串参数和字典(字符串,字符串)参数的方法,然后在您的方法中迭代字典以提取参数名称和值。字符串参数可以是您的 SP 的名称。只是一个想法!
  • 我建议不要使用字符串字典,而是使用 sql 参数的通用列表。这样它就可以独立于数据类型,而不是强制所有内容都字符串化。
  • 同意,只需每次将每个参数都提供给 SP(即不能利用默认值/可选参数)。只是一个设计考虑:)

标签: c# sql-server stored-procedures computer-science


【解决方案1】:
    public DataTable RunSP_ReturnDT(string procedureName, List<SqlParameter> parameters, string connectionString)
    {
        DataTable dtData = new DataTable();
        using (SqlConnection sqlConn = new SqlConnection(connectionString))
        {
            using (SqlCommand sqlCommand = new SqlCommand(procedureName, sqlConn))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                if (parameters != null)
                {
                    sqlCommand.Parameters.AddRange(parameters.ToArray());
                }
                using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                {
                    sqlDataAdapter.Fill(dtData);
                }
            }
        }
        return dtData;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-24
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    相关资源
    最近更新 更多