Link to home
Create AccountLog in
Avatar of baxtalo
baxtalo

asked on

SQL Server Syntax - Search Date

I would like to search dates in my SQL Server database. My WHERE clause looks like this:
Where DayRequested like '%" & Request.Form("MyDay") & "%'
The date I'm searching for is in the database, but my query still won't return any results.
The date is 'datetime' in my database. Would you please let me know what's wrong with my query?
Thank you very much...
Avatar of baxtalo
baxtalo

ASKER

I've noticed that if I search 11/08/2011 it will find my date. But my date picker enters the date as 11/8/2011.
Is there a way to convert the date format somehow in the query so that it finds my date the way it is stored in the database?
2011-11-08 00:00:00.000
Avatar of Armand G
Use CONVERT(DATETIME, @yourdatetimevalue).

e.g.
You can put into the SQL Server script the date time from datepicker by replacing the string below with your date time value:

SELECT CONVERT(DATETIME, '11/8/2011')
> Where DayRequested like '%" & Request.Form("MyDay") & "%'

Sounds like a very good opportunity for SQL-injection. Please adapt your code.

Anyway, for SQL-queries I prefer the format "yyyy/mm/dd", that almost never fails. The steps I would take are:
1. Convert the Request-value to a (sub)type Date. If that fails (for example when someone tries SQL-injection), report back to the user that he entered an invalid date.
2. Convert the Date to a string in the format "yyyy/mm/dd" by something like:
    Year(yourDate) & "/" & Month(yourDate) & "/" Day(yourDate)
    and use that string in the query.

Avatar of baxtalo

ASKER

I tried the following but shomething must be wrong with the syntax. It returns dates like 11/13/2011 but it wont' return days with single digits like 11/8/2011

Where CONVERT(varchar(10),DayRequested,101) like '%' + CONVERT(varchar(10),'%" & Request.Form("MyDay") & "%',101) + '%'
it is because you've converted it into a string rather than to a DATE at first. So in your code above you can change it like this:

Where CONVERT(varchar(10), CONVERT(DATE, DayRequested)) like '%' + CONVERT(varchar(10), CONVERT(DATE, '" & Request.Form("MyDay") & "'), 101) + '%'

You should be fine!!!
Avatar of baxtalo

ASKER

Unfortunately this won't return anything; not even the double digit days.
ASKER CERTIFIED SOLUTION
Avatar of Armand G
Armand G
Flag of New Zealand image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of baxtalo

ASKER

Thank you very much, your solution is perfect. I've learned a lot.