-1

I am Working in ASP.NET and SqlServer.

I have two textboxes with calender extender in my application where user will select two dates.I want to get data between those two dates from sqlserver where my datatype for that particular field is DateTime. please tell me how to proceed with this ...I wrote a query but thats not working..

my query:

  SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn);
John Woo
  • 258,903
  • 69
  • 498
  • 492
coder
  • 1,980
  • 3
  • 21
  • 32
  • whats the problem? any error or exception... – Waqas Raja Jan 16 '13 at 07:41
  • The answers here might help you : http://stackoverflow.com/questions/207190/sql-server-string-to-date-conversion –  Jan 16 '13 at 07:43
  • Don't use text representation for dates. Convert the input to `DateTime` first and then use that for the comparison. Also, don't build your queries like that; use parameters. – Mr Lister Jan 16 '13 at 07:43

3 Answers3

8

things to do

  • parameterized the query to prevent from sql injection
  • use using statement to properly dispose the object
  • use try-catch block to handle excpetion

eg,

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()
        }
    }
}

SOURCES

John Woo
  • 258,903
  • 69
  • 498
  • 492
1

use this code:

Sqlcommand cmd=new sql command ("Select data from tablename 
                                where date>=startdate 
                                and date<=enddate",connection)
bonCodigo
  • 14,268
  • 1
  • 48
  • 91
0

Try this

SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN '" + textbox1.Text + "' AND '" + textbox2.Text + "'

godwin
  • 1