如果您“意外”(温柔,这是一个艰难的早晨)从具有主键的表中删除一行,是否可以使用之前的键重新插入记录,即使表自动递增主键?
答案 0 :(得分:2)
/****
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
功能会在INSERT
或REPLACE
语句中未提供值时指定值。否则,如果您提供的值与现有密钥不冲突,则将按原样接受。