1

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

4

2 回答 2

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

于 2013-05-28T18:35:35.300 回答
1

如果or语句中未提供值,则该AUTO_INCREMENT功能将分配一个值。否则,如果您提供了一个值并且它与现有的键不冲突,它将被原样接受。INSERTREPLACE

于 2013-03-28T19:19:10.943 回答