How to add an index or primary key to a user-defined table type in SQL Server?

前端 未结 2 1675
陌清茗
陌清茗 2021-02-11 16:07

I have this user-defined type that I would like to add a primary key or index to:

IF NOT EXISTS (
  SELECT * 
  FROM sys.types st 
  JOIN sys.schemas ss 
    ON          


        
相关标签:
2条回答
  • 2021-02-11 16:23

    Why not this?

    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     
      );
    

    or

    CREATE TYPE [dbo].[DistCritGroupData] AS TABLE
      (
        [DistCritTypeId] [int] NOT NULL,
        [ItemAction] [int] NOT NULL,        
        [ObjectId] [int] NOT NULL,
        [OperatorType] [int] NOT NULL,
        PRIMARY KEY CLUSTERED ([DistCritTypeId] ASC)        
      );
    

    CREATE TYPE does not allow naming of contraints. Like table variables.

    0 讨论(0)
  • 2021-02-11 16:36

    @bernd_K and @gbn's answers work if it's a single column PK. For multi column, it would be:

    CREATE TYPE [dbo].[DistCritGroupData] AS TABLE
      (
        [DistCritTypeId] [int] NOT NULL,
        [ItemAction] [int] NOT NULL,        
        [ObjectId] [int] NOT NULL,
        [OperatorType] [int] NOT NULL,
        PRIMARY KEY (ColumnA,ColumnB)
      );
    

    In short, you can have PKs and UNIQUE table constraints, but you cannot name them. This kind of makes sense, since you're going to be creating multiple objects of the same type, and the only time you're going to want to work with these constraints would be an alteration of the entire table type.

    You also cannot define indexes, since those are primarily an artifact around physical storage.

    0 讨论(0)
提交回复
热议问题