views:

161

answers:

2

I want to store a C#.NET ulong into a T-SQL database. I don't see any provisions for doing this, as the SQL bigint has the same Min/Max values as a normal long.

Is there any way I can do this? Or is catching an OverflowException my only hope?

+2  A: 

I know it's not the same, but would this do:

select convert(decimal(38, 0), 12345678901234567890123456789012345678)

The maximum for an unsigned long seems to be 18,446,744,073,709,551,615 which is significantly less than this decimal can store. There might be issues converting, but I'm sure that a couple of wrapper functions in your application would sort it pretty quickly.

Jonathan
Good approach for accommodating the range of a ulong, however be aware that sql reports that decimal(38,0) takes up 17 bytes.
BC
Are you saying it's oversize for the amount of data we want to store?
Jonathan
@Johnathan: I think so. `decimal(38,0)` is more than double the size of `bigint` (2.125 times, actually) . If space was an issue, I'd be a little concerned.
Onion-Knight
+3  A: 

This should answer your question:

http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/ff08c190-a981-4896-9542-3f64b95a84a2/

You would use BigInt, you just have to be careful in how you convert the signed type back into an unsigned type in C#

// This has not been tested
unchecked
{
    myUlong = myDataReader.GetInt64(...);
}

...

The other possibility is to use VarBinary with a length of 8, then convert the bytes to a ulong in C#

Neil N
Do you have code for the conversion?
Robert Harvey
@Robert Harvey: I posted a short example
Neil N
Do you mean treating `long.MinValue` as `0` and `long.MaxValue` as `ulong.MaxValue`?
Onion-Knight
Is the behavior for the signed bit defined properly here? If you don't want to lose precision, you have to use the sign bit as the additional high-order bit in the ulong. Will this do that?
Robert Harvey
@Robert Harvey: thats why it's unchecked. High order bit doesnt matter to ulong, it just wants the 8 full bytes.
Neil N