I am developing one web application using asp.net 2005 and Microsoft SQL Server 2008. I need a help for fetching the data from database between a given range.
the date field in my table is of type VARCHAR(25) and the date format stored is dd-mm-yyyy. when I using the between clause in the SQL query then it is not giving all the data i.e. the date criteria in where clause is not working fine.
while my clients requirement is to keep the date format as dd-mm-yyyy and fetch the data according to the given range.
so please help me out with that what should I do in this case.
SQL query :
@datefrom varchar(15), // parameter in the procedure
@dateto varchar(15)
set @sql = '';
set @sql = @sql + 'SELECT * FROM ven_timesheetreportmaster vtsrm WITH (nolock)
INNER JOIN ven_descriptionmaster_timesheet vdmts ON vdmts.description_id = vtsrm.description_id '
set @sql = @sql + ' WHERE vtsrm.entry_date BETWEEN ''' + @datefrom + ''' AND ''' + @dateto + ''' '
if ( @emp_id !='0')
set @sql = @sql + ' AND vtsrm.emp_id =' + @emp_id + ' '
In the ven_timesheetreportmaster table, the entry_date is a varchar datatype..
If I pass values ,
@date from : 01-05-2011
@date to : 31-05-2011
it showing me all the values in the db from april to till date
You have a string comparison on the varchar(25), not a date comparison so exactly as expected. That is, the string ’06-06-2011′ is before the string ’31-05-2011′
Add some CONVERTs with style 112 and compare actual dates.
Or fix your data… the format
dd-mm-yyyyshould be set in the client code and the database should be native date/time types.