如何在同一查询中使用 where 条件时计算表中的行数

本文关键字:条件 计算 where 查询 | 更新日期: 2023-09-27 18:34:34

如何在同一查询中使用 where 条件时计算表中的行数。我使用以下查询来获取部门名称等于电气工程的行数。但是现在正在工作,正确的查询是什么

SqlCommand cmd1 = new SqlCommand("Select count(*) from Student
where DepartmentName = 'DepartmentOfElectricalEngineering' ");
cmd1.Connection = conn;
studentdata[4] = cmd1.ExecuteScalar().ToString();

如何在同一查询中使用 where 条件时计算表中的行数

信息不多。ExecuteScalar函数返回什么?无?有例外吗?什么是studentdata[4]?ExecuteScalar 返回一个对象,您需要根据字段(在本例中为int(和存储它的变量来强制转换该对象。您是否尝试直接针对 SQL Server 运行此查询?您是否尝试过指定显式字段名称,如下所示:

Select count(*) as C from Student
where DepartmentName = 'DepartmentOfElectricalEngineering'