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

时间:2010-12-15 14:39:32

标签: 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
    )        
  );

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

4 个答案:

答案 0 :(得分:48)

为什么不呢?

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

答案 1 :(得分:17)

@bernd_K和@ gbn的答案是有效的,如果它是单列PK。对于多列,它将是:

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

简而言之,你可以拥有PK和UNIQUE table constraints,但你无法命名它们。这种方式是有道理的,因为您将要创建多个相同类型的对象,并且您唯一想要使用这些约束的时候将改变整个表类型。

您也无法定义索引,因为这些索引主要是围绕物理存储的工件。

答案 2 :(得分:4)

您可以像这样指定类型:

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

我从未理解为什么数据库人员需要主键名称。它们应该被称为表xyz的主键。

答案 3 :(得分:0)

值得注意的是,您现在可以使用新的内联索引语法在SQL 2014中的表类型中添加某些索引。例如:

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