2013-05-28 41 views
0

[只是分享...]很久以前,DB没有参考约束,有人从PK-autoincrementing表中强制删除了一个职员,这将不允许PK关闭。孤立了一堆数据,我不得不重新插入与以前的PK值的行。数据库不允许表结构更改,但允许重命名。TSQL重新插入已删除的行w/a PK

回答

0

不知道你的意思是自动递增或为什么它不允许'PK关闭',我们不能真正提出一个不同的解决方案。

如果通过自动递增来表示IDENTITY,那么您可以使用SET IDENTITY_INSERT OFF来允许显式插入标识值。

+0

这种情况涉及到遗留系统,所以我不知道底层设置。当我使用Design并且在PK身份列上尝试将身份规范(身份)从“是”更改为“否”时,数据库将使用符号排除“保存”:不允许保存更改。您所做的更改需要删除并重新创建或启用以下表格[原文如此]选项预防保存需要重新创建表格的更改.'并列出我刚刚尝试修改的表格 – gordon

+1

在在SSMS中查询窗口,键入'SET IDENTITY_INSERT YourTable ON'。您现在将被允许更新并在您的标识列中插入值。完成后,键入“SET IDENTITY_INSERT YourTable OFF”,该字段将再次自动增加。这不是特定的数据库设置,而是您发布的命令。你绝对无法从设计窗格中做任何事情。你为什么不做一些研究并提供更多信息,那么我们可以进一步提供帮助。 –

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 @[email protected]+1 
end 

然后改名为mainTable归档和protoTable到mainTable。如果任何人有一个这样做的狡猾的方式,我很想看到它。