SQL equivalent of C# BigInteger

2019-02-18 22:14发布

问题:

So, I've been using the new BigInteger class introduced in .NET 4 to store incredibly large numbers.

Now, I've started thinking about saving these numbers to the database (SQL Server). My question is, is this even possible? As far as I know and what I've researched, the SQL data types do not contain a property that corresponds to the behaviour of BigInteger (theoretically no min or max).

The closest I've seen is bigint, but that has a minimum of -2^63 (-9,223,372,036,854,775,808) and a maximum of 2^63-1 (9,223,372,036,854,775,807).

回答1:

If your SQL server's DECIMAL type does not support the precision you need you'll only have the option to store the number as a string or a binary, i.e. in a VARCHAR, TEXT or VARBINARY field.



回答2:

You could store the result of calling yourBigInt.ToByteArray() in a VARBINARY(…), subsequently retrieving it using the BigInteger(byte[]) constructor.

The main disadvantage of this approach is that SQL Server would be restricted in its ability to work with the values as numbers (probably limited to comparing them). Then again, that's a foregone conclusion for anything that won't fit into a bigint.