Reputation: 1569
Could please anyone tell me how I can do the date comparison in where clause of a sql stored procedure.
I have a provided a text box filter to the user where user can enter date in any format (e.g. 13/09/2013, 13092013, 13-Sep-2013, 130913). The DB table has datetime type column on which I want to apply this filter to.
Here I have 3 questions
A code example will really be appreciated.
Kind Regards
Upvotes: 1
Views: 1165
Reputation: 33839
Answers:
(1). You should force user to enter in a CERTAIN FORMAT. If you don't know the entering format, how do you know if 12-11-2013
12th of November or 11th of December? This is just a one example.
If you know the user entering format, you can either convert it to a date in the code or pass as a string in ISO FORMAT (yyyymmdd
) into the stored procedure.
First method would be better as if the user input is not a valid date then you could stop calling the stored procedure.
(2). Your code behind receives the user input as a string. So you can check it in code behind like;
bool isNull = string.IsNullOrWhiteSpace(userEnteredDate);
(3). in your stored procedure
--Rest of the query
WHERE Convert(date, yourdateColumn) = @yourDateParameter
Upvotes: 2