在平時的開發中,常常會用到基於某個時間段的查詢,例如選擇開始日期、結束日期.(yyyy-MM-dd格式),而在資料庫表中該列儲存的格式卻是(yyyy- MM-dd HH:MM:SS)格式,這樣就要用到如下轉換
sbSql.Append(string.Format(" AND Convert(Char(10),RegisterDate,120)<='{0}'", endRegisterDate) );
1public DataTable GetOvertureDocInfoList(string boName, int isSend, string startRegisterDate, string endRegisterDate)
2 {
3 try
4 {
5 string strSql = "SELECT * FROM GovInfo_OvertureDocument WHERE '1'='1' ";
6 StringBuilder sbSql = new StringBuilder(strSql);
7
8 if (isSend > -1)
9 {
10 sbSql.Append(string.Format(" AND IsSend={0}",isSend));
11 }
12
13 if (startRegisterDate != "")
14 {
15 sbSql.Append(string.Format(" AND Convert(Char(10),RegisterDate,120)>='{0}'", startRegisterDate));
16 }
17 if (endRegisterDate != "")
18 {
19 sbSql.Append(string.Format(" AND Convert(Char(10),RegisterDate,120)<='{0}'", endRegisterDate));
20 }
21
22 //if (status != "")
23 //{
24 // sbSql.Append(string.Format("AND Status={0}", status));
25 //}
26
27 sbSql.Append(" ORDER BY registerdate DESC");
28
29 SqlDBAccess dbaccess = new SqlDBAccess();
30 DataSet ds = new DataSet();
31 ds = dbaccess.ExecuteDataset(boName, CommandType.Text, sbSql.ToString());
32 DataTable dt = ds.Tables[0];
33
34 return dt;
35 }
36 catch (Exception e)
37 {
38 LogUtil.Log.Error(this, e);
39 throw e;
40 }
41 }