Cannot insert explicit value for identity column in table ‘table’ when IDENTITY_INSERT is set to OFF

reprinted from  http://sqlserverplanet.com/sql-server/cannot-insert-explicit-value-for-identity-column-in-table-table-when-identity_insert-is-set-to-off/

just for self-learning.

 

Cannot insert explicit value for identity column in table ‘table’ when IDENTITY_INSERT is set to OFF.

This error occurs when trying to insert into a column containing an identity. An Identity column is not able to be inserted into without the use of a special command mentioned below. Identity columns are columns that automatically increment when a value is inserted into a row. They are commonly used as primary keys because they guarantee uniqueness.

In order to insert into a table containing an identity column

SET IDENTITY INSERT ‘tablename’ ON

IDENTITY INSERT ON can only be executed by a user having dbo privilidges

The following example illustrates the error and shows how to successfully insert.

-- Create MyNames Table with Identity Column
CREATE TABLE dbo.MyNames
(
    ID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    FName varchar(50) NULL
)
  
INSERT INTO dbo.MyNames
(
    FName
)
SELECT 'Abe'
UNION
SELECT 'Henry'
UNION
SELECT 'Phil'
  
-- Create YourNames Table with Identity Column
CREATE TABLE dbo.YourNames
(
    ID int IDENTITY(4,1) NOT NULL PRIMARY KEY, --Start Incrementing at 4
    FName varchar(50) NULL
)
  
INSERT INTO dbo.YourNames
(
    FName
)
SELECT 'Bill'
UNION
SELECT 'Candy'
UNION
SELECT 'Sara'
  
-- Attempt to Insert MyNames Identity Into YourNames
INSERT INTO dbo.YourNames
(
    ID,
    FName
)
SELECT
    ID,
    Fname
FROM dbo.MyNames
  
-- we get the error message:
Cannot insert explicit value for identity column in table 'YourNames' when IDENTITY_INSERT is set to OFF.
  
-- Attempt to Insert after turning on IDENTITY_INSERT ON
SET IDENTITY_INSERT dbo.YourNames ON
  
INSERT INTO dbo.YourNames
(
    ID,
    FName
)
SELECT
    ID,
    Fname
FROM dbo.MyNames
  
SET IDENTITY_INSERT dbo.YourNames OFF

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值