Unsigned Integer Datatype in SQL Server 2005
There's been some interesting questions by users on the SQL Server Engine Tips blog. While almost all of them seem to be off topic, there are some interesting ideas. One of the fun ones was from Dave asking "Can we have some unsigned int data types?".
As a basic background for those of us who spend most of their time in T-SQL; an unsigned integer does not hold negative values. The value range is from 0 to the maximum of the datatype.
So assuming Dave is wanting unsigned integers for this reason, here is how you would create unsigned integer user datatypes in SQL Server 2005:
CREATE TYPE dbo.unsignedTinyint FROM tinyint NULL
CREATE TYPE dbo.unsignedSmallint FROM smallint NULL
CREATE TYPE dbo.unsignedInt FROM int NULL
CREATE TYPE dbo.unsignedBigint FROM bigint NULL
/* unsigned integer (positive values only) rule */
CREATE RULE dbo.unsignedSmallIntRule AS @value >= 0;
CREATE RULE dbo.unsignedIntRule AS @value >= 0;
CREATE RULE dbo.unsignedBigintRule AS @value >= 0;
/* Bind the unsigned integer rules to their datatypes */
EXEC sp_bindrule 'dbo.unsignedSmallIntRule', 'dbo.unsignedSmallint'
EXEC sp_bindrule 'dbo.unsignedIntRule', 'dbo.unsignedInt'
EXEC sp_bindrule 'dbo.unsignedBigintRule', 'dbo.unsignedBigint'
You can download the sample script here which includes an example table with the new unsigned integer data types.
If you attempt to insert an negative value into an unsigned column, you will receive an error message like:
A column insert or update conflicts with a rule imposed by a previous CREATE RULE statement. The statement was terminated.
Aritmetic overflow error for data type tinyint, value =-1.