[只是分享...]很久以前DB没有参考限制,有人从PK-autoincrementing表中删除了一个不允许PK关闭的人员。孤立了一堆数据,我不得不重新插入前一个PK值的行。 DB不允许更改表结构,但允许重命名。
答案 0 :(得分:0)
这就是我的所作所为:
/****
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重命名为archive,将protoTable重命名为mainTable。如果有人有这样做的方式,我很乐意看到它。
答案 1 :(得分:0)
如果不知道自动递增的确切含义或不允许'PK关闭'的原因,我们无法真正提出不同的解决方案。
如果通过自动递增表示IDENTITY,则可以使用SET IDENTITY_INSERT OFF
来允许显式插入标识值。