C#调用存储过程获取查询结果时Count=0问题排查求助
C#调用存储过程返回空集合?问题出在这!
你遇到的问题核心很明确——你的C#代码根本没读取存储过程返回的结果集,还错用了执行方法,难怪返回的集合Count是0。咱们一步步拆解问题:
先看你的C#代码核心问题
你当前用了cmd.ExecuteNonQuery(),这个方法是用来执行不返回结果集的SQL命令(比如INSERT、UPDATE、DELETE),它返回的是受影响的行数,完全不处理查询结果。而且你从头到尾都没把存储过程返回的name和LastAccessedDate数据映射到CertificationSummary集合里,最后返回的只是初始化的空列表,Count自然为0。
修复后的C#代码
把执行方法换成SqlDataReader读取结果,再把数据填充到集合中:
private List<CertificationSummary> GetLastAccessData(string taskOwner) { List<CertificationSummary> lastAccessedResult = new List<CertificationSummary>(); string connectionString = SqlPlusHelper.GetConnectionStringByName("MetricRepositoryDefault"); using (SqlConnection connection = new SqlConnection(connectionString)) { SqlParameter[] sqlParams = new SqlParameter[1]; sqlParams[0] = new SqlParameter("@taskOwner", SqlDbType.NVarChar); sqlParams[0].Value = taskOwner; connection.Open(); using (SqlCommand cmd = connection.CreateCommand()) { cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "GetLastAccessedCertificationData"; cmd.Parameters.AddRange(sqlParams); // 用SqlDataReader读取存储过程返回的结果集 using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { CertificationSummary summary = new CertificationSummary(); // 注意和你的CertificationSummary类属性对应,假设属性为Name和LastAccessedDate summary.Name = reader["name"].ToString(); // 处理日期类型,避免DBNull异常 if (!reader.IsDBNull(reader.GetOrdinal("LastAccessedDate"))) { summary.LastAccessedDate = reader.GetDateTime(reader.GetOrdinal("LastAccessedDate")); } lastAccessedResult.Add(summary); } } } } return lastAccessedResult; }
额外优化:简化你的存储过程
其实你的存储过程没必要用临时表和中间变量,一次关联查询就能得到结果,既高效又避免了空值风险:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[GetLastAccessedCertificationData] (@taskOwner nvarchar(255)) AS BEGIN SELECT TOP(1) crc.Name AS name, urca.LastAccessedDate FROM CertificationReviewCycles crc INNER JOIN UserReviewCycleAccess urca ON crc.CertificationReviewCycleID = urca.LastAccessedReviewCycleID WHERE urca.USERID = @taskOwner END GO
内容的提问来源于stack exchange,提问作者oni3619
相关产品推荐
相关产品推荐

