¿Cómo activar y desactivar IDENTITY INSERT usando SQL Server 2008?


¿Por qué recibo un error al hacer una inserción cuando IDENTITY_INSERT está configurado en OFF?

¿Cómo lo enciendo correctamente en SQL Server 2008? ¿Es mediante el uso de SQL Server Management Studio?

He ejecutado esta consulta:

SET IDENTITY_INSERT Database. dbo. Baskets ON

Luego recibí el mensaje en la consola que el Comando(s) se completó con éxito. Sin embargo, cuando corro la aplicación, todavía me da el error que se muestra a continuación:

Cannot insert explicit value for identity column in table 'Baskets' when 
IDENTITY_INSERT is set to OFF.
Author: SteveC, 2011-08-15

7 answers

Vía SQL según MSDN

SET IDENTITY_INSERT sometableWithIdentity ON

INSERT sometableWithIdentity (IdentityColumn, col2, col3, ...)
VALUES (AnIdentityValue, col2value, col3value, ...)

SET IDENTITY_INSERT sometableWithIdentity OFF

El mensaje de error completo le dice exactamente lo que está mal...

No se puede insertar un valor explícito para la columna de identidad en la tabla 'sometableWithIdentity' cuando IDENTITY_INSERT está establecido en OFF.

 573
Author: gbn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-04 16:06:16

Tuve un problema en el que no me permitía insertarlo incluso después de configurar IDENTITY_INSERT.

El problema era que yo no especificar los nombres de columna y, por alguna razón, no le gustaba.

INSERT INTO tbl Values(vals)

Así que básicamente hacer la INSERCIÓN completa EN tbl (cols) Valores (vals)

 46
Author: Ismael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-08 14:56:38

Importación: Debe escribir columnas en la instrucción INSERT

INSERT INTO TABLE
SELECT * FROM    

No Es correcto.

Insert into Table(Field1,...)
Select (Field1,...) from TABLE

Es correcto

 28
Author: R.Alonso,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-22 09:58:46

Sé que este es un hilo más antiguo, pero me encontré con esto. Si el usuario está tratando de ejecutar insertos en la columna Identidad después de alguna otra sesión Establecida IDENTITY_INSERT EN, entonces está obligado a obtener el error anterior.

Establecer el valor Identity Insert y los siguientes comandos Insert DML se ejecutarán en la misma sesión.

Aquí @Principiante estaba configurando la inserción de identidad por separado y luego ejecutando las inserciones desde su aplicación. Es por eso que obtuvo la siguiente Error:

Cannot insert explicit value for identity column in table 'Baskets' when 
IDENTITY_INSERT is set to OFF.
 1
Author: aok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-22 07:35:08

Esto es probable cuando tiene un campo de CLAVE PRIMARIA y está insertando un valor que se está duplicando o tiene la bandera INSERT_IDENTITY establecida en on

 0
Author: seanyp20001,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-20 14:46:50

Parece imposible poner una base de datos IDENTITY_INSERT. dbo. Cestas activadas; antes de cada lote de envío de insertos SQL. / Puede enviar varios INSERT ... VALOR .. los comandos comenzaron con un CONJUNTO IDENTITY_INSERT ... ON; cadena al principio. Simplemente no pongas ningún separador de lotes entre/ No se porque el SET IDENTITY_INSERT ... ON deja de funcionar, después del bloque de envío(por ej.: .ExecuteNonQuery() en c#)... Tuve que poner SET IDENTITY_INSERT ... ON; otra vez al principio del siguiente comando SQL cadena.

 -1
Author: Jettero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-08 20:08:34

Necesita agregar el comando 'go' después de configurar la inserción de identidad. Ejemplo:

SET IDENTITY_INSERT sometableWithIdentity ON
go

INSERT sometableWithIdentity (IdentityColumn, col2, col3, ...)
VALUES (AnIdentityValue, col2value, col3value, ...)

SET IDENTITY_INSERT sometableWithIdentity OFF
go
 -6
Author: Bruce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-03 06:48:36