IDENTITY (propiedad de Transact-SQL)

Crea una columna de identidad en una tabla. Esta propiedad se usa con las instrucciones CREATE TABLE y ALTER TABLE de Transact-SQL.

[!NOTA]

La propiedad IDENTITY no es la misma que la propiedad Identity de SQL-DMO que expone la propiedad de identidad de las filas de una columna.

Icono de vínculo a temasConvenciones de sintaxis de Transact-SQL

Sintaxis

IDENTITY [ (seed , increment) ]

Argumentos

  • seed
    Es el valor que se utiliza para la primera fila cargada en la tabla.

  • increment
    Se trata del valor incremental que se agrega al valor de identidad de la anterior fila cargada.

Debe especificar tanto el valor de inicialización como el incremento, o bien ninguno de los dos. Si no se especifica ninguno, el valor predeterminado es (1,1).

Notas

Si hay una columna de identidad para una tabla en la que se realizan eliminaciones frecuentemente, pueden quedar espacios entre los valores de identidad. Si esto constituye un problema, no utilice la propiedad IDENTITY. Sin embargo, para asegurarse de que no se han creado espacios o para rellenar un espacio existente, evalúe los valores de identidad existentes antes de escribir uno explícitamente con SET IDENTITY_INSERT establecido en ON.

Si vuelve a utilizar un valor de identidad eliminado, utilice el código del ejemplo B para buscar el siguiente valor de identidad disponible. Reemplace tablename, column_type y MAX(column_type) - 1 por el nombre de la tabla, el tipo de datos de la columna de identidad y el valor numérico del valor máximo permitido (para ese tipo de datos), -1.

Utilice DBCC CHECKIDENT para comprobar el valor de identidad actual y compararlo con el valor máximo de la columna de identidad.

Si una tabla con una columna de identidad se publica para replicarla, la columna de identidad debe administrarse de manera apropiada para el tipo de replicación utilizado. Para obtener más información, vea Replicar columnas de identidad.

Ejemplos

A. Utilizar la propiedad IDENTITY con CREATE TABLE

En el siguiente ejemplo se crea una nueva tabla con la propiedad IDENTITY para un número de identificación que se incrementa automáticamente.

USE AdventureWorks
IF OBJECT_ID ('dbo.new_employees', 'U') IS NOT NULL
   DROP TABLE new_employees
GO
CREATE TABLE new_employees
(
 id_num int IDENTITY(1,1),
 fname varchar (20),
 minit char(1),
 lname varchar(30)
)

INSERT new_employees
   (fname, minit, lname)
VALUES
   ('Karin', 'F', 'Josephs')

INSERT new_employees
   (fname, minit, lname)
VALUES
   ('Pirkko', 'O', 'Koskitalo')

B. Utilizar la sintaxis genérica para buscar espacios en los valores de identidad

En este ejemplo se muestra la sintaxis genérica utilizada para buscar espacios en valores de identidad cuando se quitan datos.

[!NOTA]

La primera parte del siguiente script de Transact-SQL se ha diseñado sólo como ejemplo. Puede ejecutar el script de Transact-SQL que comienza por el comentario: -- Create the img table.

-- Here is the generic syntax for finding identity value gaps in data.
-- The illustrative example starts here.
SET IDENTITY_INSERT tablename ON
DECLARE @minidentval column_type
DECLARE @maxidentval column_type
DECLARE @nextidentval column_type
SELECT @minidentval = MIN($IDENTITY), @maxidentval = MAX($IDENTITY)
    FROM tablename
IF @minidentval = IDENT_SEED('tablename')
   SELECT @nextidentval = MIN($IDENTITY) + IDENT_INCR('tablename')
   FROM tablename t1
   WHERE $IDENTITY BETWEEN IDENT_SEED('tablename') AND 
      @maxidentval AND
      NOT EXISTS (SELECT * FROM tablename t2
         WHERE t2.$IDENTITY = t1.$IDENTITY + 
            IDENT_INCR('tablename'))
ELSE
   SELECT @nextidentval = IDENT_SEED('tablename')
SET IDENTITY_INSERT tablename OFF
-- Here is an example to find gaps in the actual data.
-- The table is called img and has two columns: the first column 
-- called id_num, which is an increasing identification number, and the 
-- second column called company_name.
-- This is the end of the illustration example.

-- Create the img table.
-- If the img table already exists, drop it.
-- Create the img table.
IF OBJECT_ID ('dbo.img', 'U') IS NOT NULL
   DROP TABLE img
GO
CREATE TABLE img (id_num int IDENTITY(1,1), company_name sysname)
INSERT img(company_name) VALUES ('New Moon Books')
INSERT img(company_name) VALUES ('Lucerne Publishing')
-- SET IDENTITY_INSERT ON and use in img table.
SET IDENTITY_INSERT img ON

DECLARE @minidentval smallint
DECLARE @nextidentval smallint
SELECT @minidentval = MIN($IDENTITY) FROM img
 IF @minidentval = IDENT_SEED('img')
    SELECT @nextidentval = MIN($IDENTITY) + IDENT_INCR('img')
    FROM img t1
    WHERE $IDENTITY BETWEEN IDENT_SEED('img') AND 32766 AND
      NOT    EXISTS (SELECT * FROM img t2
          WHERE t2.$IDENTITY = t1.$IDENTITY + IDENT_INCR('img'))
 ELSE
    SELECT @nextidentval = IDENT_SEED('img')
SET IDENTITY_INSERT img OFF