I have designed a basic search in ASP/C# for searching through records in a database and have provided the user with these fields which they can use to search: word/phrase, dateFrom, dateTill. So entering “Hello, World!”, 05/25/2009, 06/25/2009 respectively will search for a database record with the contents “Hello, World!” which was created between the given dates. Pretty simple stuff.
The text entered by the user into the fields is injected directly into an SQL statement like follows:
SELECT r.idRecord, r.recordText
FROM record r
WHERE LOWER(CAST(r.recordText AS VARCHAR)) LIKE LOWER('%" + word/phrase + "%')
AND r.creationDate BETWEEN '" + dateFrom + "' AND '" + dateTill + "'"
So still pretty simple and it works like a charm when the user enters dates in an American format, mm/dd/yyyy. However, it fails when a date in British format is entered like, 25/05/2009. Finally…
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS [DD/MM/YYYY]
…doesn’t particularly help because I don’t want to select the date, can a similar statement be used in the WHERE clause?
Thanks for the help.
Parse the value entered by the user into a
DateTimedata type using the DateTime.ParseExact method. This method allows you to specify the format of the datetime, so you can usedd/MM/yyyyorMM/dd/yyyy, depending on your user’s preferences. Then pass the DateTime value as a parameter to your SQL statement.Here is a blog post that explains
Coding Horror: Give me parameterized SQL, or give me death