SQL Server’s CREATE TYPE DDL statement supports at least two different ways of declaring the PRIMARY KEY constraint and other options.
-
The simplest is an inline
PRIMARY KEYmodifier on a single column (see the<column_definition>syntax rule, and theCLUSTERED/NONCLUSTEREDkeyword is optional).CREATE TYPE dbo.DistCritGroupData AS TABLE ( DistCritTypeId int NOT NULL PRIMARY KEY CLUSTERED, ItemAction int NOT NULL, ObjectId int NOT NULL, OperatorType int NOT NULL );-
Note that
UNIQUEandCHECKconstraints can also be declared on a single column. For example:CREATE TYPE dbo.DistCritGroupData AS TABLE ( DistCritTypeId int NOT NULL PRIMARY KEY CLUSTERED, ItemAction int NOT NULL, ObjectId int NOT NULL UNIQUE, OperatorType int NOT NULL CHECK ( OperatorType >= 1 AND OperatorType <= 10 ) );
-
-
You can also declare the
PRIMARY KEY,UNIQUE, andCHECKconstraints as a table-type constraint, located right after the column definitions:-
You must use this approach if you have a composite
PRIMARY KEY– or if you want to reference multiple columns in yourUNIQUEorCHECKconstraint. -
Unlike in a normal
CREATE TABLEstatement these constraints are always anonymous and lack theCONSTRAINTkeyword.- i.e. use just
PRIMARY KEY ( DistCritTypeId, ItemAction )but notCONSTRAINT PK_DistCritGroupData PRIMARY KEY ( DistCritTypeId, ItemAction ).
CREATE TYPE dbo.DistCritGroupData AS TABLE ( DistCritTypeId int NOT NULL, ItemAction int NOT NULL, ObjectId int NOT NULL, OperatorType int NOT NULL, PRIMARY KEY ( DistCritTypeId ), UNIQUE ( ObjectId ), CHECK ( OperatorType >= 1 AND OperatorType <= 10 ) ); - i.e. use just
-
-
You can also specify additional arbitrary
INDEXobjects, which are declared after thePRIMARY KEYconstraint (if any).-
Unlike
CREATE TABLEDDL statements, you cannot useCREATE INDEXto define an index on a table-type; theINDEXdefinition must be part of theCREATE TYPEstatement. -
Also, unlike the
PRIMARY KEY,CHECK, andUNIQUEconstraints we’ve seen so far,INDEXobjects on table-types are not anonymous.CREATE TYPE dbo.DistCritGroupData AS TABLE ( DistCritTypeId int NOT NULL, ItemAction int NOT NULL, ObjectId int NOT NULL, OperatorType int NOT NULL, PRIMARY KEY ( DistCritTypeId ), INDEX IX_ObjectId_OperatorType ( ObjectId, OperatorType ) );
-
-
Note there is no
FOREIGN KEYconstraint type here: table-types cannot participate in foreign-key constraints.