views:

44

answers:

3

I have something like this:

foo { a = 1, b = 2, c = 98,3 }

I generate the insert query dynamically so end up with this:

insert foos(a,b,c) (1, 2, 98,3)

anybody knows how to workaround this ?

A: 

Can you not just cast the value to something with a '.'?

Edit: using parameterized queries would be better. And a simple 'Replace' would help as well.

Tobiasopdenbrouw
the value is decimal in the first place, after i cast her to string, you mean to do like this d.ToString().Replace(",",".") ?
Omu
Sure, something like that.
Tobiasopdenbrouw
+5  A: 

Simple answer: don't use text to insert values in the first place. Use a parameterized SQL query.

This isn't limited to numbers - it's also particularly important for dates and times. Conceptually, you're not dealing with a "number with a comma in" - you're dealing with a number. SQL happens to be the way we transfer data between the database and the client, but parameterized SQL allows us to keep the values as values without a pointless and error-prone conversion to text in between. Finally, parameterized queries are highly important as a guard against SQL injection attacks when transferring text values.

Basically, separate out the idea of "values" (which go in parameters) and "SQL code" which stays in text.

Just reformatting existing SQL which contains values until it happens to work is a brittle solution at best.

Jon Skeet
Jon's answer has more value than you might think at first glance, omu.
Tobiasopdenbrouw
u mean like this: command.Parameters.AddWithValue("@c", foo.c) ?
Omu
@Omu: Quite possibly, having adjusted the SQL statement appropriately, of course.
Jon Skeet
@Tobiasopdenbrouw ya, according to his rating, his answers should be auto-accepted :)
Omu
+1  A: 

When generating SQL strings always use .ToString(CultureInfo.InvariantCulture) to ensure that decimals are formatted correctly for TSQL.

Or, for preference, use parameterised queries as Jon Skeet suggests above.

Dr Herbie
thank you for telling me that, I didn't know about this usage of tostring
Omu