Click here to Skip to main content
15,901,666 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In sql server 2008, my table structure like this and i need to retrieve records based on fromdate and todate

ID Text ValidFrom ValidTo
2 A 2/3/2015 2/7/2015
3 C 2/5/2015 2/6/2015
4 B 1/21/2015 1/23/2015
5 D 1/23/2015 1/24/2015


if fromdate='02/04/2015' and todate='02/06/2015' then
expecting result as
ID Text ValidFrom ValidTo
2 A 2/3/2015 2/7/2015
3 C 2/5/2015 2/6/2015
Posted
Comments
Richard MacCutchan 19-Feb-15 7:06am    
If you are storing the dates as text strings then you will always have a problem.

Not sure if you have solved this problem already, but in my honest opinion you should never store dates in varchar. This would lead you to problems whenever you need to compare the values, calculate it etc. You always end up to converting the text values back to dates and then doing the actual operation.

When you have converted the values then your query should be something like:
SQL
SELECT ...
FROM ...
WHERE @fromDateValue BETWEEN ValidFrom AND ValidTo
OR    @toDateValue BETWEEN ValidFrom AND ValidTo
 
Share this answer
 
You can filter dates like following
SQL
SELECT ID.Text,ValidFrom,ValidTo
FROM [YourTableName]
WHERE ValidFrom BETWEEN '02/04/2015' AND '02/06/2015' 
--OR--WHERE ValidTo BETWEEN '02/04/2015' AND '02/06/2015'

But, this will definitely not give the result as you have shown because as you want result like
ID Text ValidFrom ValidTo
2 A 2/3/2015 2/7/2015
3 C 2/5/2015 2/6/2015 

but '2/3/2015' or '2/7/2015' of first row doesn't match with filter date range '02/04/2015' and '02/06/2015'

If you want something else, please let me know :)
 
Share this answer
 
v2
Comments
raviendiran 19-Feb-15 7:14am    
thanks for your help, but even-though i have another scenario when i am passing fromdate='02/05/2015' and todate='02/05/2015' then i need to retrieve records which ever matching validfrom and validto dates
Suvendu Shekhar Giri 19-Feb-15 7:39am    
So, what I understood,
(1) either you need the result such that "ValidFrom"="FromDate" or "ValidTo"="ToDate"
(2) or you need the result such that "ValidFrom" between "FromDate" and "ToDate"
or "ValidTo" between "FromDate" and "ToDate"
Please clarify a little more so that I will be able to help you :)
Try following command-

SQL
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900