MySQL⾃增列插⼊0值的⽅法
在将数据库从MSSQL迁移到MySQL的过程中,基于业务逻辑的要求,需要在MySQL的⾃增列插⼊0值。在MSSQL中是这样完成的:
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
This mode can be useful if0 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 ne 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
⼤致的意思是说: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) ";session数据错误是什么意思
⾄此问题解决。
后记:
由于业务逻辑需要,在⾃增列会存在0值,为了在Windows平台和Linux平台的MySQL之间复制数据,增加全局变量设置,在my.ini和myf中分别添加
NO_AUTO_VALUE_ON_ZERO设置到sql-mode⾏,例如:
/
/my.ini 该⽂件在Windows7或Windows2008操作系统中位于 C:\ProgramData\MySQL\MySQL Server 5.6 ⽬录下(采⽤MSI安装⽅式)
# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,NO_AUTO_VALUE_ON_ZERO"
重启MySQL服务后,查看sql-mode全局变量的办法:
SELECT @@GLOBAL.sql_mode;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。