2013-05-28 37 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。如果任何人有一個這樣做的狡猾的方式,我很想看到它。