954,560 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Get Records between two dates

I have a table in which i have a column named "dtCreated" which has got datatype as VARCHAR(50)

Now I want records between two dates.

I wrote my query as written below

select * from mytable where dtcreated>=fromdate and dtcreated<=todate


This query work fine when fromdate and ToDate are of same month. i.e if fromDate =1/1/2011
and todate is 1/31/2011 it will work fine

But if fromdate is 1/1/2011 and todate is 2/1/2011 then no records will be returned.

Please give me solution of it

MARKAND911
Junior Poster
126 posts since Nov 2008
Reputation Points: 10
Solved Threads: 2
 

Use BETWEEN and cast the varchar to date:

select * from mytable where dtcreated BETWEEN CAST(fromdate AS DATE) and CAST(todate AS DATE)


Edit: This works on SQL Server 2008 and up. Cast to datetime if you are using an earlier version.

buddylee17
Practically a Master Poster
697 posts since Nov 2007
Reputation Points: 232
Solved Threads: 137
 

You simply need to understand why your query failed.

To compare, you need dates not strings.

debasisdas
Posting Genius
6,872 posts since Feb 2007
Reputation Points: 666
Solved Threads: 434
 

In the below given example,you just need to specify
1> Your Table name from any specific MSSQL database
2> 'ColumnName' as a table field,that should be in datetime or date format in the table
Example

<strong>select * from [yourTableName]
where  (CAST(ColumnName AS date) >= '2006-01-18') and (CAST(ColumnName AS date) <= '2006-02-18')</strong>


Enjoy... :)

Akash Saikia
Junior Poster
112 posts since Mar 2011
Reputation Points: 19
Solved Threads: 20
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: