Mysql 意外地从具有主键的表中删除了行

Mysql 意外地从具有主键的表中删除了行,mysql,Mysql,如果您无意中表现得很温和,那么从具有主键的表中删除一行是一个艰难的早晨,即使该表自动增加主键,是否可以使用其上一个键重新插入记录 如果INSERT或REPLACE语句中未提供值,则自动增量功能将指定一个值。否则,如果您提供的值与现有键不冲突,它将按原样被接受。TSQL我有一个非常奇怪的环境-在某些方面非常受限,而在其他方面则非常开放。不允许插入已使用的PK值,必须重新创建整个表 /**** create protoTable w/ same structure as your mainTable

如果您无意中表现得很温和,那么从具有主键的表中删除一行是一个艰难的早晨,即使该表自动增加主键,是否可以使用其上一个键重新插入记录

如果INSERT或REPLACE语句中未提供值,则自动增量功能将指定一个值。否则,如果您提供的值与现有键不冲突,它将按原样被接受。

TSQL我有一个非常奇怪的环境-在某些方面非常受限,而在其他方面则非常开放。不允许插入已使用的PK值,必须重新创建整个表

/****
create protoTable w/ same structure as your mainTable that has the data you are trying to fix in this example the fieldname of the primary key is FldPK
assumption here is that your primary key is getting auto incremented
get a list of the fields in the mainTable that are NOT NULL.
in this example those fields are <not null fields>
get a list of all fields in the mainTable
in this example <all fields>, rather than spell out the fields. DO NOT INCLUDE the primary key field name
***/
declare @x int, @y int, @iLast int
select @iLast = (select MAX( FldPK ) from mainTable)
set @x = 1
while @x <= @iLast
begin
  select @y = (select COUNT(*) from mainTable where FldPK = @x)
  if @y = 1
    begin
      insert into protoTable(<all fields>)
        select <all fields> from mainTable where FldPK = @x
    end
  else
    begin
      insert into protoTable (<not null fields> )values('N','xyz'+convert(varchar,@x)) /*or whatever values are valid to fulfill not null*/
      /* this is where you keep one or more of the missing rows to update later with the lost data */
      if @x <> 126
        begin
          delete protoTable where FldPK = @x
        end
    end
  set @x=@x+1
end
然后将mainTable重命名为backup,并将protoTable重命名为mainTable


是的,这是可能的。你试过了吗?我的一个用户犯了一个edge case错误,我现在已经通过验证修复了这个错误。但它是在一个生产环境中,所以我不想尝试插入,直到我确定能够为该行设置pk。