MySQL自增列插入0值的方法 在將數據庫從MSSQL遷移到MySQL的過程中,基於業務邏輯的要求,需要在MySQL的自增列插入0值。在MSSQL中是這樣完成的: www.2cto.com string sql; sql = " set identity_insert dbo.AppUsers on " + " insert dbo.AppUsers (Id, IsLocked, IsMustChangeLocalPassword, IsAvailable, Name, Sequence, CreatedBy, CreatedTime, UpdatedBy, UpdatedTime) " + " values (0, 1, 0, 0, '[SYSTEM]', 0, 0, GetDate(), 0, GetDate()) " + " set identity_insert dbo.AppUsers off " + " DBCC CHECKIDENT ('dbo.AppUsers', RESEED, 0) "; db.Database.ExecuteSqlCommand(sql); MySQL官方文檔中是這樣寫的: NO_AUTO_VALUE_ON_ZERO affects handling of AUTO_INCREMENT columns. Normally, you generate the next sequence number for the column by inserting either NULL or 0 into it. NO_AUTO_VALUE_ON_ZERO suppresses this behavior for 0 so that only NULL generates the next sequence number. This mode can be useful if 0 has been stored in a table's AUTO_INCREMENT column. (Storing 0 is not a recommended practice, by the way.) For example, if you dump the table with mysqldump and then reload it, MySQL normally generates new sequence numbers when it encounters the 0 values, resulting in a table with contents different from the one that was dumped. Enabling NO_AUTO_VALUE_ON_ZERO before reloading the dump file solves this problem. mysqldump now automatically includes in its output a statement that enables NO_AUTO_VALUE_ON_ZERO, to avoid this problem. 大致的意思是說:NO_AUTO_VALUE_ON_ZERO會影響自增列,一般情況下,獲得下一個序列值的方法是對自增列插入0或者NULL值。NO_AUTO_VALUE_ON_ZERO會改變這個缺省的行為,使得只有插入NULL值才能獲取下一個序列值。這種方式對於要將0值插入自增列是有用的。(順便指出,0值是不推薦使用在自增列的)例如,如果你使用mysqldump備份數據表然後再恢復它,MySQL一般情形下會0值自動產生新的序列值,結果是造成從備份恢復數據錯誤。在恢復數據前,啟用NO_AUTO_VALUE_ON_ZERO可以解決這個問題。mysqldump現在會自動在輸出的語句中包含NO_AUTO_VALUE_ON_ZERO來解決這個問題。 在MySQL中需要這樣: sql = " SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO'; insert AppUsers (Id, IsLocked, IsMustChangeLocalPassword, IsAvailable, Name, Sequence, CreatedBy, CreatedTime, UpdatedBy, UpdatedTime) " + " values (0, 1, 0, 0, '[SYSTEM]', 0, 0, CURRENT_TIMESTAMP, 0, CURRENT_TIMESTAMP) "; 至此問題解決。