報錯:Cannot insert explicit value for identity column in table 't' when identity_insert is set to OFF


通常情況下,不能向 SQL Server 自增字段插入值,如果非要這么干的話,SQL Server 就會好不客氣地給你個錯誤警告:

  1. Server: Msg 544, Level 16, State 1, Line 1  
  2. Cannot insert explicit value for identity column in table 't' when identity_insert is set to OFF. 

這個錯誤消息提示我們,如果向 SQL Server 自增字段插入值,需要設置 identity_insert 選項為 on。

  1. set identity_insert on 

看具體的一個例子:

 

  1. create table dbo.t  
  2. (  
  3. id int identity(1,1) not null,  
  4. name varchar(50)  
  5. )  
  6. set identity_insert t on  
  7. insert into t (id, name) values(1, 'sqlstudy')  
  8. set identity_insert t off  

注意的是,自增字段插入值后,要及時把 identity_insert 設置為 off。

 

或者寫插入語句時不要把自增的ID加入進去。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM