How to reorder auto increment column values, after deleting any row other than last row?

走远了吗. 提交于 2019-12-13 07:22:34

问题


I want to know is there any SQL query for asp.net,c# that can just re arrange auto increment coloumn values..

eg. deleting 2 in the table:

sno

1

2

3

4

does:

sno

1

3

4

but i want re-arrangement:

sno

1

2

3

Note:

  1. Don't want to to the numbering manually
  2. query to create table is like this:

CREATE TABLE uid (sno int IDENTITY(1,1) PRIMARY KEY, qpname nvarchar(500), mob int, tm int)


回答1:


Let your table be named Parent and table that will hold the backup is called Backup. They should have identical columns.

INSERT INTO dbo.Backup 
    SELECT * FROM dbo.Parent

Now truncate the parent table

TRUNCATE TABLE dbo.Parent

Now you can just insert the data back using the first command and just reversing the table names.

Remember that this may not work in all cases. You may have On delete cascade on and if that is the case, then you would loose all data from other tables also which are referencing the parent table. I think that you should never use this is you are using any Foriegn Key reference on this table.




回答2:


Following are the queries which should run 1 after other to get this functionality done. This can be easily achieved in C# by executing a generic ExecuteNonQuery().

DELETE FROM TBL1 WHERE sno = @sno; 

UPDATE TBL1
SET sno = sno -1
WHERE sno > @sno;


来源:https://stackoverflow.com/questions/43232822/how-to-reorder-auto-increment-column-values-after-deleting-any-row-other-than-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!