2011-11-25 63 views
0

我在我的表測試這樣我日期列的類型爲varchar的記錄。如何在日期範圍內查看記錄?

Fname  Lname  Date 
vivek  parikh  01-09-2011 10:00:00 PM 
kashyap vyas  02-09-2011 10:50:00 AM 
viral  panchal 02-09-2011 10:00:00 PM 
Arpit  Gosai  03-09-2011 10:00:00 PM 
Darshit Chokshi 04-09-2011 10:00:00 PM 
Sameer  Rangrez 24-08-2011 9:15:12 AM 

我想從頁面的日期範圍(開始日期和結束日期)中獲取記錄。

我的代碼是

DateTime time = DateTime.Today;    // Use current time 
    string format = "MM-dd-yyyy"; 

    SqlCommand cmd = new SqlCommand("select Fname,Lname,Insert_Date from Test where Insert_Date >= '" + Convert.ToDateTime(TextBox1.Text).ToString(format) + "' and Insert_Date <= '" + Convert.ToDateTime(TextBox2.Text).ToString(format) + "' ", con); 
    DataSet ds = new DataSet(); 
    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    da.Fill(ds); 

    for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
    { 
     Response.Write(ds.Tables[0].Rows[i]["Fname"].ToString()); 
     Response.Write(ds.Tables[0].Rows[i]["Lname"].ToString()); 
     Response.Write(ds.Tables[0].Rows[i]["Insert_Date"].ToString()+"<br>"); 
    } 
+2

你嘗試過什麼的C#這麼遠嗎?哪個版本?短LINQ語句應該給你一個非常好的解決方案。 – Matten

+0

從數據庫這個拉?如果那麼,什麼數據庫是嗎?或者它保存在內存中? –

+0

是其從SQL Server 2008 R2 .. –

回答

1

建立查詢使用Convert(日期時間,字段名,103)轉換爲varchar爲datetime。

您的查詢應該是這樣的。

SELECT * FROM測試 其中轉換(日期時間,field_date,103)> = '2011-01-01' --start日期

轉換(日期時間,field_date,103)< =' 2012-01-01'; --end日期

這是你的C#語句應該怎麼樣子(它應該包括代碼指定

SqlCommand cmd = new SqlCommand("select Fname,Lname,Insert_Date from Test where Convert(datetime,Insert_Date,103) >= '" + Convert.ToDateTime(TextBox1.Text).ToString(format) + "' and Convert(datetime,Insert_Date,103) <= '" + Convert.ToDateTime(TextBox2.Text).ToString(format) + "' ", con); 
+0

它給了我「爲datetime數據類型varchar數據類型的轉換導致一個超出範圍的值「 –

+0

你得到它,因爲我忘記了爲你的日期指定樣式編號103。請參閱以下鏈接瞭解樣式格式[鏈接] http://www.sqlusa.com/bestpractices/datetimeconversion/ – Habib

0

SELECT colname的FROM表名WHERE somecol> = '2011-01-09' AND somecol < = '2011-09-24'

+0

比較它沒有工作,獲取準確的日期sql查詢!請給我從上表中詳細的解決方案.. –

+0

是一個SQL數據庫。張貼一些代碼,你已經嘗試 – Karthik

+0

看到編輯問: –

0

SELECT * FROM Test其中,日期> ='2011-09-02'和日期<'2011-0-04'

0

檢出BETWEEN SQL運算符。另外,請確保使用標準SQL Server格式正確地格式化日期以避免和潛在的混淆:yyyymmdd hhmmss,並記住還要考慮日期的時間部分。

0

下面的SQL語句已經過測試,其中DD-MM-YYYY的日期格式對我們公司的SQL Server 2008和工作正常。

SELECT * 
FROM some_table 
WHERE date_field >= '2011-10-25' and date_field <= '2011-11-26' 
相關問題