DataSet中无法按自定义表名访问DataTable的问题求助
问题根源与解决方案
问题核心:存储过程的输出参数
@tables只是返回了一个包含表名的字符串,ADO.NET不会自动将这个字符串拆分并设置DataSet中DataTable的TableName属性。DataSet默认会按查询结果顺序给表命名为Table、Table1、Table2,所以用自定义名称访问会找不到对应表。解决步骤:
- 调用存储过程时,同时获取DataSet和输出参数返回的表名字符串
- 将表名字符串拆分为单个名称的数组
- 遍历DataSet的Tables集合,为每个DataTable设置对应的自定义名称
修改后的代码示例
// 调用存储过程,同时获取DataSet和输出参数的表名 ProgramProcedures procedures = new ProgramProcedures(); string tableNames; DataSet ds = procedures.GetTestByUser(UserId, out tableNames); // 拆分表名字符串为数组 string[] nameArray = tableNames.Split(','); // 为DataSet中的每个表设置自定义名称 for (int i = 0; i < ds.Tables.Count && i < nameArray.Length; i++) { ds.Tables[i].TableName = nameArray[i].Trim(); // 去除可能的空格 } // 现在可以正常用自定义表名访问了 if (ds.Tables["Name1"].IsHasRows()) { foreach (DataRow _dr in ds.Tables["Name1"].Rows) { TestList.Add(new Test(_dr)); } }
补充:修改存储过程调用方法以获取输出参数
如果你的GetTestByUser方法原本没有处理输出参数,需要先更新方法逻辑,添加对@tables参数的处理:
public DataSet GetTestByUser(int userId, out string tableNames) { DataSet ds = new DataSet(); using (SqlConnection conn = new SqlConnection("你的数据库连接字符串")) { SqlCommand cmd = new SqlCommand("你的存储过程名称", conn); cmd.CommandType = CommandType.StoredProcedure; // 添加输入参数 cmd.Parameters.AddWithValue("@UserId", userId); // 添加输出参数 SqlParameter tableParam = new SqlParameter("@tables", SqlDbType.NVarChar, -1) { Direction = ParameterDirection.Output }; cmd.Parameters.Add(tableParam); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(ds); // 获取输出参数的值 tableNames = tableParam.Value?.ToString() ?? string.Empty; } return ds; }
内容的提问来源于stack exchange,提问作者MarkB
相关产品推荐
相关产品推荐

