我试图按月获得警报统计数据。这是我的SQL语句
SELECT datepart(year,incidentDate),datepart(month,incidentDate) ,COUNT(*) AS CNT
From alarm_actions,alarm_licenses
where licType = 'AR' and alarm_actions.alarmNo = ALARM_LICENSES.alarmNo and alarmCount > 0 and
ignoreAlarm = 0 and incidentDate between '5/1/12' and '7/31/14'
group by datepart(year,incidentDate) , datepart(month,incidentdate)
order by datepart(year,incidentDate)
当我在SQL 2008R2中执行此查询时,我得到27行,但是当我在Visual Studios中使用SqlDataReader时,我得不到任何数据。 chartFrom和chartTo是我用来获取日期的文本框。
string alarmCount = ("Select datepart(year,incidentDate) , datepart(month,incidentDate),COUNT(*) as cnt From Alarm_Actions,Alarm_Licenses Where licType = 'AR' and alarm_actions.alarmNo = alarm_licenses.alarmNo and alarmCount > 0 and ignoreAlarm = 0 and incidentDate between " + chartFromDate + " and " + chartToDate + "group by DATEPART(YEAR, incidentDate), DATEPART(MONTH,incidentDate) order by DATEPART(YEAR, incidentDate)");
SqlDataReader dr = data.myDataReader(alarmCount);
while(dr.Read())
{
//Do something
}
以下是myDataReader的代码
public SqlDataReader myDataReader(string mSQL)
{
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataReader myReader;
SqlCommand myCommand1;
try
{
myConnection.Open();
//myCommand1 = new System.Data.OleDb.OleDbCommand(mSQL, myConnection);
myCommand1 = new SqlCommand(mSQL, myConnection);
//=============== 1/26/2012 =============
//There have been errors running recently. I am increasing the timeout here
myCommand1.CommandTimeout = 60000;
myReader = myCommand1.ExecuteReader(CommandBehavior.CloseConnection);
//return myReader;
}
catch (Exception e1)
{
MessageBox.Show("An error occurred retrieving the requested data\r\n\r\n" + mSQL + "\r\n\r\n" + e1.Message);
myReader = null;
try
{
string mSentBy = ConfigurationManager.AppSettings["emailSentBy"].ToString();
string mSendTo1 = ConfigurationManager.AppSettings["emailSendTo"].ToString();
string mSubject = ConfigurationManager.AppSettings["emailSubject"].ToString();
string mHost = ConfigurationManager.AppSettings["emailHost"].ToString();
string mSignon = ConfigurationManager.AppSettings["emailSignon"].ToString();
string mPassword = ConfigurationManager.AppSettings["emailPassword"].ToString();
}
catch { }
}
finally
{
//myConnection.Close();
myCommand1 = null;
//myReader = null;
myConnection = null;
//myReader = null;
}
return myReader;
}
感谢您的帮助
我在日期字段中丢失了'。感谢大家花时间帮忙
答案 0 :(得分:1)
我没有测试它,但我希望它适合你:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT datepart(year,incidentDate), ......";
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
//Do something
}
con.Close();