[英]Retrieve Data From DataTable
我正在运行一个SQL查询,它将返回查询的计数
Select Count(numstudents) from classA
我正在使用C#
连接到SQL Server并执行此查询,但是我的问题是,如何获取返回的实际数字? 我当前的方法返回DataTable
的行数,默认情况下始终为1。我需要返回Count()
。
这是完整的C#
语法:
private void GetData()
{
DataSet ds = new DataSet()
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand("RunAStoredProc", con))
{
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(ds);
}
}
}
DataTable table1 = new DataTable();
table1 = ds.Tables[0];
DataTable table2 = new DataTable();
table2 = ds.Tables[1];
string numberreturned = table1.Rows.Count.ToString();
Console.WriteLine(numberreturned);
Console.ReadKey();
}
存储过程如下所示:
Alter Procedure [dbo].[GetData]
As
Select Count(*) FROM classA
Select studentfirstname, studentlastname FROM classA
Where enrolled = 'Yes'
如果您只有存储过程返回的单个值,则不需要SqlDataAdapter和使用所有必需的基础结构。 只需使用ExecuteScalar
int count = 0;
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand("RunAStoredProc", con))
{
cmd.CommandType = CommandType.StoredProcedure;
count = (int)cmd.ExecuteScalar();
}
Console.WriteLine(count);
Console.ReadKey();
但是,如果您确实要使用适配器和数据集,则可以从读取的表的第一行和第一列中读取值来查找查询结果
int count = Convert.ToInt32(table1.Rows[0][0]);
甚至(不声明table1变量)
int count = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
要发现第一个选择语句的结果与第二个选择语句返回的行数之间的差异,您可以编写
int allStudents = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
int enrolledStudents = ds.Tables[1].Rows.Count;
int notEnrolledStudents = allStudents - enrolledStudents;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.