.NET decimal value cause SqlTruncateException on SQL Server

hec6srdp  于 2023-03-28  发布在  .NET
关注(0)|答案(2)|浏览(134)

I have a .NET app that sends a table-valued parameter to a SQL Server stored procedure.

In the SQL Server table, the column is defined as DECIMAL(20,0) .

Table-valued column on .NET defined as

Columns.Add(new SqlMetaData(name, SqlDbType.Decimal));

When sending a 20 or 19 digit long .net decimal value like this Convert.ToDecimal(81210694789319013214) , SQL Server throws an exception:

SqlTruncateException: Numeric arithmetic causes truncation

On a 18 digits long decimal, it works just fine.

There's not much documentation about this error online.

Thanks

1u4esq0p

1u4esq0p1#

If you are using EF

Set DecimalPropertyConfiguration.HasPrecision Method as per the link Decimal precision and scale in EF Code First

kqlmhetl

kqlmhetl2#

You haven't showed us any code - so this is purely speculative. But just maybe, check your stored procedure parameter for the decimal value - how is it defined?

Did you just use DECIMAL without providing any precision and scale values?

If so: DECIMAL defaults to DECIMAL(18,0) - which would explain why it works with 18 digit numbers, but not with 20 digits.

You need to explicitly define the precision and scale to use - Best Practice is to do this ALWAYS anyway!

CREATE PROCEDURE dbo.InsertDecimal
    @InputDecimal DECIMAL(20,0)     -- define 20 digits, 0 after decimal point
AS
  .....

With this - everything should work just fine ....

The official Microsoft documentation on DECIMAL will tell you more details

相关问题