1

I have web application in asp.net 4.0 am using calender control for "FromDate" when am going to fetch my records then my query is as follows:

Select * 
From Sec_RoleFeatures
Where RoleId = 39 
  and FeatureCode = 'MR' 
  and FromDate='12/12/2012 11:05:05 AM'

as this `FromDate field date format does not match with sql format so result is that it does not give records give null.

so in this case what can I do? how to match my date format with sql date format?

0

4 Answers 4

5

Don't pass the value in the SQL at all. Use parameterized SQL for all values like this. Benefits:

  • The SQL is cleaner (no mixing of code and data)
  • Avoids SQL injection attacks (probably not relevant here, but definitely for strings)
  • Avoids conversion issues

Fundamentally, avoid string conversions where you can. Not just in database work, but in general. Try to keep your data in its "natural" type (DateTime here) for as long as possible. In this case you don't need to convert it to a string at all (as you can use parameters) so why do so?

See the documentation for SqlCommand.Parameters for an example of how to use parameters in your SQL.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, Yes, You are absolutely right, I recommended the way YYYYMMDD in case the date entry is entered directly, not from a C# application.
1

Use the reverse ISO format: yyyymmdd (so 12/12/2012 is 20121212) and use 24 hr format for time.

Select * From Sec_RoleFeatures Where (RoleId = 39) and (FeatureCode = 'MR') and (FromDate = '20121212 11:05:05')

Comments

0

try use

Select * From Sec_RoleFeatures Where RoleId = 39 and FeatureCode = 'MR' and  CONVERT(varchar(10),FromDate,101)='12/12/2012'

2 Comments

It's works but not completely it not given Time means '12/12/2012 11:05:05 AM'
If you have to do a conversion, prefer to convert strings to dates rather than dates to strings. And try to avoid ambiguous formats.
0

Try Casting :

Select * From Sec_RoleFeatures Where RoleId = 39 and FeatureCode = 'MR' and 
CAST(FromDate AS DATE) = CAST('12/12/2012 11:05:05 AM' AS DATE)

The advantage here is, it will compare only the dates ignoring the time part.

1 Comment

I don't want to ignore time part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.