I am having problem with negative decimal.
In a SQL Server database I have defined price as decimal(8,2) NULL
and the code I am using in C#:
string query = string.Format("INSERT INTO ticket_elements " +
"(ticket_id, product_name, price, tax, amount) " +
VALUES ({0}, '{1}', '{2}', '{3}', '{4}'); SELECT SCOPE_IDENTITY();",
ticket_id, pro2.ProductName, tPrice, tax, fixedAmountStr);
When {2} also the price not negative value is, then its working fine but when I set the price like -0.25 then its giving this error:
Arithmetic Overflow on converting varchar in numeric-datatype.
What do I need to do to use negative values in db?
Update:
but the following code just working fine with negative or positive values.
I am really confused.
string query = string.Format("INSERT INTO tickets " +
"(registration_date, cancellation, cancellation_date, total_products, total_gross_price, total_net_price, pay_type, user_id, client_id)" +
" VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', {7}, {8});" +
" SELECT SCOPE_IDENTITY();", regData, "False", "", this.TotalProducts, totalGrossPrice, totalNetPrice, this.PayType, this.CashierId, this.ClientId);
Use parameterized queries instead. It saves you from injection attacks, and is actually faster han passing in straight SQL with hardcoded values (because the server can cache the compiled parameterized query and only sends the values). This is how you’d do it:
Just be warned that if you pass in a string, it will have to perform the conversion on the DB side, which can fail if it can’t convert it. Better thing to do would be to get the strongly typed values (in other words, parse the amounts to make sure they’re valid) and then pass those values into the parameters.