通常情況下,不能向 SQL Server 自增字段插入值,如果非要這么干的話,SQL Server 就會好不客氣地給你個錯誤警告:
- Server: Msg 544, Level 16, State 1, Line 1
- Cannot insert explicit value for identity column in table 't' when identity_insert is set to OFF.
這個錯誤消息提示我們,如果向 SQL Server 自增字段插入值,需要設置 identity_insert 選項為 on。
- set identity_insert on
看具體的一個例子:
- create table dbo.t
- (
- id int identity(1,1) not null,
- name varchar(50)
- )
- set identity_insert t on
- insert into t (id, name) values(1, 'sqlstudy')
- set identity_insert t off
注意的是,自增字段插入值后,要及時把 identity_insert 設置為 off。
或者寫插入語句時不要把自增的ID加入進去。