[只是分享...] 很久以前,DB 没有参考限制,有人从不允许 PK 关闭的 PK 自动增量表中硬删除了一个员工。孤立了一堆数据,我不得不重新插入具有前 PK 值的行。DB 不允许更改表结构,但允许重命名。
问问题
67 次
2 回答
0
在不知道自动递增的确切含义或它为什么不允许“PK 关闭”的情况下,我们无法真正提出不同的解决方案。
如果通过自动递增您的意思是 IDENTITY,那么您可以使用SET IDENTITY_INSERT OFF
允许显式插入身份值。
于 2013-05-29T01:50:33.987 回答
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
然后将归档和 protoTable 的 mainTable 重命名为 mainTable。如果有人有更巧妙的方法,我很乐意看到它。
于 2013-05-28T19:20:42.117 回答