Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User defined type for unsigned 64-bit value vs NUMERIC(20,0)

Let's say I want to create a table that has some columns which I want to contain 64-bit unsigned integers. I can go about this several different ways, some of which may not be valid or have consequences:

  1. Use NUMERIC(20,0) and add a check constraint that makes sure that the value is not negative and is within the bounds of a 64-bit unsigned integer (i.e., >=0 and <18,446,744,073,709,551,616). Furthermore, the logic of the check constraint can be encapsulated in a UDF so as to avoid redundancy.
  2. Create a CLR User Defined Type that encapsulates this logic (and ultimately wraps a System.UInt64). Use the type for both column types and Stored Procedure parameters. Would such a type give me greater capability (e.g., by preventing invalid values from being passed into a stored proc at the call site)?
  3. Reuse the BCL System.UInt64 type. Would this even be possible?

I am looking for someone who is knowledgeable in the capabilities/integration of SQLCLR to assess my ideas, above and comment on the best course of action.

Thanks

like image 427
Michael Goldshteyn Avatar asked Mar 18 '26 06:03

Michael Goldshteyn


1 Answers

Use numeric(20,0) and a check constraint to restrict 0 <= x <= 18446744073709551615 (fixed on edit)

SQL Server does not have unsigned 64 but integer so you'd have to do some logic in the client to make it appear int not decimal

The upper check limit is needed because 19E18 is more then unsigned 64 but OK for numeric(20,0). This may not be desirable if the DB values overflows and breaks in the client.

And if you decide that you need an extra few zeros you can change to numeric (23, 0) or higher...

like image 187
gbn Avatar answered Mar 24 '26 18:03

gbn