sql-server – 如何在SQL Server中为用户定义的表类型添加索引或主键?

我有这个用户定义的类型,我想添加一个主键或索引到:

IF NOT EXISTS (
  SELECT * 
  FROM sys.types st 
  JOIN sys.schemas ss 
    ON st.schema_id = ss.schema_id 
  WHERE st.name = N'DistCritGroupData' 
    AND ss.name = N'dbo')
BEGIN

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

END;
GO  

我基本上想要添加主键或聚集索引。我试过这个,但是我收到错误’找不到对象“dbo.DistCritGroupData”,因为它不存在或您没有权限。

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

我在对象浏览器中看到我的用户定义的表类型,有“列”,“键”,“约束”和“索引”的部分。问题是,我如何添加键或索引?

为什么不这样?

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

要么

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不允许命名的约束。像表变量。

http://stackoverflow.com/questions/4451052/how-to-add-an-index-or-primary-key-to-a-user-defined-table-type-in-sql-server

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:sql-server – 如何在SQL Server中为用户定义的表类型添加索引或主键?