2010-12-15 11 views
24

que tienen este tipo definido por el usuario que me gustaría añadir una clave principal o el índice que:¿Cómo agregar un índice o clave principal a un tipo de tabla definida por el usuario en 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 

básicamente gustaría o bien agregar una clave principal o un índice agrupado. Intenté esto pero recibí el error "No se puede encontrar el objeto" dbo.DistCritGroupData "porque no existe o no tienes permisos.

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

que ver en el Explorador de objetos en mi definida por el usuario tipo de tabla que hay secciones de "Columnas", "claves", "limitaciones" y "índices". La pregunta es, ¿cómo puedo agregar una clave o índice?

Respuesta

38

¿Por qué no esto?

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

o

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 no permite nombres de contraints. Como las variables de tabla.

3

Puede especificar el tipo de la siguiente manera:

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

Nunca supe por qué las personas necesitan de bases de datos de nombres de claves primarias. Deberían llamarse La clave principal de la tabla xyz.

+1

¿La "clave principal de la tabla xyz" es un identificador válido? Necesita algún nombre para sys.objects .. – gbn

+0

@gbn Es absolutamente único y puede evaluar el nombre único generado de las tablas del sistema, si es necesario. –

+2

Necesita una clave o restricción con nombre cuando está trabajando con el control de origen. Entonces las claves o restricciones con nombre son muy útiles. – eghetto

15

Las respuestas de @bernd_K y @ ​​gbn funcionan si se trata de una PK de una sola columna. Por varias columnas, sería:

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

En resumen, se puede tener PK y único table constraints, pero no se puede nombrarlos. Esto tiene sentido, ya que vas a crear varios objetos del mismo tipo, y la única vez que vas a querer trabajar con estas restricciones sería una alteración de todo el tipo de tabla.

Tampoco puede definir índices, ya que estos son principalmente un artefacto en torno al almacenamiento físico.

Cuestiones relacionadas