Kennet Madsen
Kennet Madsen

Reputation: 11

Incorrect syntax near ','. error

I am getting an SQL error when I try to do this:

    public static int GetOrderId(decimal totalprice, int userid)
    {
        string s = "SELECT * from orders where OrderUserId = " + userid + " and OrderTotalPrice = " + totalprice;
        cmd = new SqlCommand(s, con);
        int temporderid = Convert.ToInt32(cmd.ExecuteScalar());

        return temporderid;
    }

As far I can see its because it gets OrderTotalPrice back, the format is incompatible. But I cant figure out how to get it in the compatible format.

Upvotes: 0

Views: 2020

Answers (2)

M4N
M4N

Reputation: 96571

I guess this is because totalprice gets converted to something like 12,35 when you concatenate the query.

Therefore, I'd suggest you use a parametrized query. E.g. like this:

var s = "SELECT * from orders " +
    " where OrderUserId = @userid and OrderTotalPrice = @totalprice";
var cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue("userid", userid);
cmd.Parameters.AddWithValue("totalprice", totalprice);

int temporderid = Convert.ToInt32(cmd.ExecuteScalar());

Upvotes: 0

Andomar
Andomar

Reputation: 238086

It's probably formatting totalprice with a comma, like 3,14, where SQL Server expects a dot, like 3.14.

One way to fix that would be to specify InvariantCulture, which uses a dot:

var s = string.Format(
    CultureInfo.InvariantCulture, 
    "SELECT * from orders where OrderUserId = {0} and OrderTotalPrice = {0:0.0}",
    42, 3.1415);

This formats the price as 3.1 on any machine.

By the way, it's much nicer to pass the variables as parameters:

var com = new SqlCommand();
com.CommandType = CommandType.Text;
com.CommandText = "SELECT * from orders where OrderUserId = @userid " +
    "and OrderTotalPrice = @totalprice";
com.Parameters.AddWithValue("@userid", 42);
com.Parameters.AddWithValue("@totalprice", 3.1415);
var temporderid = com.ExecuteScalar();

Then you don't have to worry about formats because you send the database a double, not a double formatted as a string.

Upvotes: 3

Related Questions