TSQL重新插入已删除的行,不带主键

TSQL重新插入已删除的行,不带主键,tsql,row,primary-key,restore,Tsql,Row,Primary Key,Restore,[只是分享…]很久以前DB没有引用约束,有人从PK自动递增表中硬删除了一个不允许关闭PK的职员。孤立了一堆数据,我不得不用以前的PK值重新插入该行。DB不允许更改表结构,但允许重命名。以下是我所做的: /**** 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

[只是分享…]很久以前DB没有引用约束,有人从PK自动递增表中硬删除了一个不允许关闭PK的职员。孤立了一堆数据,我不得不用以前的PK值重新插入该行。DB不允许更改表结构,但允许重命名。

以下是我所做的:

/****
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和protoTable重命名为mainTable。如果有人有更巧妙的方法,我很想看看。

不知道自动递增是什么意思,也不知道为什么它不允许“PK关闭”,我们真的无法提出不同的解决方案


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

这种情况涉及遗留系统,因此我不知道底层设置。当我使用Design并在PK identity列上尝试将identity Specification Is identity从Yes更改为No时,DB禁止使用以下符号进行保存:不允许保存更改。您所做的更改需要删除并重新创建或启用以下表格[sic]此选项可防止保存需要重新创建表格的更改。它列出了我刚才试图修改的表,在SSMS的查询窗口中,键入SET IDENTITY\u INSERT YourTable ON。您现在可以在标识列中更新和插入值。完成后,键入SET IDENTITY\u INSERT YourTable OFF,该字段将再次自动递增。这不是特定的数据库设置,而是您发出的命令。在设计窗格中,您绝对不能执行任何操作。你为什么不做些调查,提供更多的信息,然后我们可以进一步帮助你呢。