1

I've got to make a query from C# and compare with a datetime. Datetime is stored in my database like this:

2014-11-09 00:00:01

and I'm using this query:

SELECT * 
FROM Table 
WHERE DATETIMEVAR = '19/11/2014 0:00:01' AND OTHERVAR = 1

But it's not in the same format. Is there a way to convert from System.DateTime in C# to dates in SQL Server, or a way to cast from SQL Server the datetime in that format?? Should I check with like instead of = in Where clause.

Thanks.

2
  • I don't think there should be any issue in passing datetime from C# to sql server. What issue are you facing ? Commented Nov 19, 2014 at 14:23
  • 1
    If you store a datetime in SQL then it has no format. Same like a DateTime in C# - it also has no format. It is not a string. Commented Nov 19, 2014 at 14:26

2 Answers 2

5

The best way would be to have a parametrized query in C#, and then set your date time parameter as a datetime (instead of relying on converting dates back and forth to and from strings).

So you should have something like:

SELECT * 
FROM Table 
WHERE DATETIMEVAR = @DateTimeValue AND OTHERVAR = 1

and then define that @DateTimeValue parameter as datetime and set it as datetime

That approach:

  • prevents any SQL injection vulnerability
  • avoid any string/formatting issues - it compares a DATETIME to a System.DateTime in their native format
Sign up to request clarification or add additional context in comments.

Comments

2

If you are generating the query from a DateTime object, just do date.ToString("yyyy-MM-dd HH:mm:ss") to convert it to that format in your query.

1 Comment

Uppercase "SS" should be lower case, dude!

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.