[只是分享...]很久以前,DB沒有參考約束,有人從PK-autoincrementing表中強制刪除了一個職員,這將不允許PK關閉。孤立了一堆數據,我不得不重新插入與以前的PK值的行。數據庫不允許表結構更改,但允許重命名。TSQL重新插入已刪除的行w/a PK
0
A
回答
0
不知道你的意思是自動遞增或爲什麼它不允許'PK關閉',我們不能真正提出一個不同的解決方案。
如果通過自動遞增來表示IDENTITY,那麼您可以使用SET IDENTITY_INSERT 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。如果任何人有一個這樣做的狡猾的方式,我很想看到它。
相關問題
- 1. tsql:刪除行爲
- 2. 帶有關係的已刪除對象由AFIncremntalStore重新插入
- 3. TSQL更新觸發器:加入插入和刪除
- 4. Python/sqlite:獲取新插入行的PK
- 5. Cassandra - 重新插入刪除的列
- 6. TSQL刪除重複的行只
- 7. SQL插入 - 已刪除表
- 8. 散列:插入已刪除的插槽
- 9. TSQL插入和刪除重複項以提高查詢性能
- 10. hibernate @ManyToMany刪除並重新插入
- 11. 刪除並重新插入ListView列(.NET)
- 12. 值刪除後不會重新插入
- 13. Mysql主鍵刪除和重新插入
- 14. 刪除行,重新編輯非PK索引列? C#
- 15. SQL Server重複使用已刪除的身份PK
- 16. JPA錯誤「無法合併已刪除的實體」試圖刪除並重新插入一行SpringData
- 17. 從JunctionTable更新/刪除TSQL
- 18. 刪除pk場
- 19. 插入/刪除行時更新表格
- 20. TSQL合併插入重複
- 21. TSQL - 選擇插入的行
- 22. 更新/刪除/插入DataGridView
- 23. 更新並插入TSQL
- 24. 使用Pelops在cassandra中刪除行後重新插入數據
- 25. tsql - 刪除最後一行
- 26. SQL Server 2008同步 - 如何用新主鍵重新插入衝突的pk行
- 27. SQLAlchemy的PK插入
- 28. 使用臨時表將已刪除的數據重新插入數據集。 Qlikview
- 29. 觸發插入行插入刪除
- 30. 刪除插入目標表中已有的新記錄
這種情況涉及到遺留系統,所以我不知道底層設置。當我使用Design並且在PK身份列上嘗試將身份規範(身份)從「是」更改爲「否」時,數據庫將使用符號排除「保存」:不允許保存更改。您所做的更改需要刪除並重新創建或啓用以下表格[原文如此]選項預防保存需要重新創建表格的更改.'並列出我剛剛嘗試修改的表格 – gordon
在在SSMS中查詢窗口,鍵入'SET IDENTITY_INSERT YourTable ON'。您現在將被允許更新並在您的標識列中插入值。完成後,鍵入「SET IDENTITY_INSERT YourTable OFF」,該字段將再次自動增加。這不是特定的數據庫設置,而是您發佈的命令。你絕對無法從設計窗格中做任何事情。你爲什麼不做一些研究並提供更多信息,那麼我們可以進一步提供幫助。 –