What is a good mapping of .NET decimal to SQL Server decimal?

前端 未结 6 1320
清酒与你
清酒与你 2021-01-03 18:08

I am having to interface some C# code with SQL Server and I want to have exactly as much precision when storing a value in the database as I do with my C# code. I use one of

6条回答
  •  暖寄归人
    2021-01-03 18:21

    The C#'s decimal type size is 128 bits (16 bytes). In SQL Server if you specify a precision between 20-28 it will use 13 bytes for storage. If you specify precision between 29-38, it will use 17 bytes for storage. For your database to be able to store the whole possible range of values for the .NET's decimal type, you would have to use the SQL Server's decimal type with a minimum precision of 29. Because any precision between 29 and 38 will use the same amount of bytes for storage (17), it is in your interest to select 38 as a precision.

    The C#'s decimal type allows you to use it without prior specification exactly what part of the precision you will use before and what part after the decimal separator. You don't have that luxury in SQL Server. The decision for the scale depends entirely on your requirements, but you have to make that decision because if you don't specify a scale it will be 0 by default and you will not be able to store floating point numbers at all.

    The above is true in case you have to be sure that you will be able to store the whole .NET decimal range.

    If you use C#'s decimal for money in your app, I think that Decimal(19, 4) will be enough.

提交回复
热议问题