0

I am trying to execute a SQL statement that grabs data within a given time period represented by two dates. Although I have verified that the values of the parameters I am swapping the SQL parameters with are the correct values, I am still getting this exception:

Syntax error converting character string to smalldatetime data type

Here is the C# code:

SqlCommand command = new SqlCommand("SELECT date, @Data FROM datasite WHERE date > '@Start' and date < '@End'", conn);

command.Parameters.AddWithValue("@Data", dataType);

var start = dateRange.StartDate.ToShortDateString();
var end = dateRange.EndDate.ToShortDateString();

command.Parameters.AddWithValue("@Start", start);
command.Parameters.AddWithValue("@End", end);

command.Connection.Open();

SqlDataReader reader = command.ExecuteReader();

while (reader.Read()) { //... }
3
  • 1
    Pass the DateTime itself? command.Parameters.AddWithValue("@Start", dateRange.StartDate); Commented May 4, 2016 at 16:33
  • Passing it as a DateTime results in the same Exception, sorry I should've mentioned that in the post. Commented May 4, 2016 at 16:37
  • Remove those single quotes when using parameters. '@Start' should just be @Start Commented May 4, 2016 at 16:43

3 Answers 3

4

A few things to consider:

  1. You do not need to cast the dates using ToShortDateString(). Instead, you can simply pass the Date variable as the parameter value: command.Parameters.AddWithValue("@Start", dateRange.StartDate);
  2. Your SqlCommand text does not need the single quotes around your @Start and @End variables. Instead, you can use: WHERE date > @Start AND date < @End
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the clear and concise response. I figured that DateTimes had to be handled like they are when writing raw SQL queries, but these changes fixed the issue.
1

Best to format the date to a known format for the sql statement eg.

   dateRange.EndDate.ToString("yyyy-MM-dd hh:mm:ss");

1 Comment

I tried a few different formats but it still results in the same Exception.
1

You might need to remove the single quotes from the command string.

"SELECT date, @Data FROM datasite WHERE date > '@Start' and date < '@End'"

To

"SELECT date, @Data FROM datasite WHERE date > @Start and date < @End"

Comments

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.