2013-01-16 73 views
-1

我在ASP.NET和SqlServer中工作。在兩個日期之間選擇數據

我在我的應用程序兩個文本框與壓延擴展其中用戶將選擇兩個dates.I想從SQLSERVER獲得這兩個日期之間的數據在我的針對特定領域的數據類型爲日期時間。請告訴我如何用這個來進行......我寫了查詢,但多數民衆贊成不工作..

我的查詢:

SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn); 
+0

什麼問題呢?任何錯誤或異常... –

+0

未選擇數據。 – coder

+0

這裏的答案可能會幫助你:http://stackoverflow.com/questions/207190/sql-server-string-to-date-conversion – devnomore

回答

1

使用此代碼:

Sqlcommand cmd=new sql command ("Select data from tablename 
           where date>=startdate 
           and date<=enddate",connection) 
7

事情要做

  • 參數化查詢從防止SQL注入
  • 使用using聲明妥善處置對象
  • 使用try-catch塊來處理錯誤時拋出

例如,

string query = @"select top 1 OrderNumber 
       from tblOrderMaster 
       where OrderedDate BETWEEN @startDate AND @endDate"; 
using(SqlConnection conn = new SqlConnection("connectionString here")) 
{ 
    using(SqlCommand cmd = new SqlCommand()) 
    { 
     cmd.Connection = conn; 
     cmd.CommandText = query; 
     cmd.Parameters.AddWithValue("@startDate", txtfromcal.Text); 
     cmd.Parameters.AddWithValue("@endDate", txttocal.Text); 
     try 
     { 
      conn.Open(); 
      // other codes 
      // to fetch the record 
     } 
     catch(SqlException e) 
     { 
      // do something with 
      // e.ToString() 
     } 
    } 
} 

來源

+0

代碼有什麼問題? –

0

試試這個

SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN ' 「+ textbox1.Text +」' 與 ' 「+ textbox2.Text +」'

相關問題