使用主键从表中意外删除的行

时间:2013-03-28 18:40:06

标签: mysql

如果您“意外”(温柔,这是一个艰难的早晨)从具有主键的表中删除一行,是否可以使用之前的键重新插入记录,即使表自动递增主键?

2 个答案:

答案 0 :(得分:2)

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

HTH

答案 1 :(得分:1)

AUTO_INCREMENT功能会在INSERTREPLACE语句中未提供值时指定值。否则,如果您提供的值与现有密钥不冲突,则将按原样接受。