0

I am getting the following error

syntax not correct near item number

but I don't see anything wrong, the values being inserted are from a dataset containing field names in variables from another sql query that is being looped through and then inserted into another table like so....

string strOrderDetails = 
    "INSERT INTO Orders (Order Number, Item Number, Description, Price) " +
    "VALUES ('" + strOrderNo.Replace("'", "''").ToString() + "', '"
             + intItemNo + "', '"
             + strDesc.Replace("'", "''").ToString() + "', '"
             + decPrice + "')";

On execution of the above is where the code falls over and states there's an error near the word item number?

Do I need to do something to the intItemNo as it's an integer?

3
  • 1
    I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Jul 15, 2013 at 22:04
  • you can try with square brackets columns that have spaces like ([Order Number], [Item Number],....) Commented Jul 15, 2013 at 22:05
  • 1
    Please please please do what Steve's answer denotes below. Parameterized queries are always a better idea. He also ensures proper disposal of your SqlCommand and SqlConnection objects with the using keyword. Commented Jul 15, 2013 at 22:45

1 Answer 1

4

When a column contains spaces you need to enclose it in square brackets or other delimiter for the choosen database

But said that, please do not use string concatenation to build sql commands, but always a parameterized query.

string strOrderDetails = "INSERT INTO Orders ([Order Number], [Item Number]," + 
                         "Description, Price) VALUES (@ordNum, @temNo, @desc, @price";
using(SqlConnection cn = new SqlConnection(conString))
using(SqlCommand cmd = new SqlCommand(strOrderDetails, cn))
{
    cn.Open();
    cmd.Parameters.AddWithValue("@ordNum",strOrderNo);
    cmd.Parameters.AddWithValue("@itemNo",intItemNo);
    cmd.Parameters.AddWithValue("@desc",strDesc);
    cmd.Parameters.AddWithValue("@price", decPrice);
    cmd.ExecuteNonQuery();
}

As you could notice, using parameters remove the need to write code to handle quotes in the input values, but also remove the possibility of Sql Injection attacks

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

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.