How to change programmatically non-identity column to identity one?

我们两清 提交于 2019-12-20 02:08:06

问题


I have a table with column ID that is identity one. Next I create new non-identity column new_ID and update it with values from ID column + 1. Like this:

new_ID = ID + 1

Next I drop ID column and rename new_ID to name 'ID'.

And how to set Identity on this new column 'ID'?

I would like to do this programmatically!


回答1:


As far as I know, you have to create a temporary table with the ID field created as IDENTITY, then copy all the data from the original table. Finally, you drop the original table and rename the temporary one. This is an example with a table (named TestTable) that contains only one field, called ID (integer, non IDENTITY):

BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_TestTable
    (
    ID int NOT NULL IDENTITY (1, 1)
    )  ON [PRIMARY]
GO
SET IDENTITY_INSERT dbo.Tmp_TestTable ON
GO
IF EXISTS(SELECT * FROM dbo.TestTable)
     EXEC('INSERT INTO dbo.Tmp_TestTable (ID)
        SELECT ID FROM dbo.TestTable WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_TestTable OFF
GO
DROP TABLE dbo.TestTable
GO
EXECUTE sp_rename N'dbo.Tmp_TestTable', N'TestTable', 'OBJECT' 
GO
COMMIT



回答2:


Looks like SQL Mobile supports altering a columns identity but on SQL Server 2005 didn't like the example from BOL.

So your options are to create a new temporary table with the identity column, then turn Identity Insert on:

Create Table Tmp_MyTable ( Id int identity....)

SET IDENTITY_INSERT dbo.Tmp_Category ON

INSERT Into Tmp_MyTable (...)
Select From MyTable ....

Drop Table myTable

EXECUTE sp_rename N'dbo.Tmp_MyTable', N'MyTable', 'OBJECT' 

Additionally you can try and add the column as an identity column in the first place and then turn identity insert on. Then drop the original column. But I am not sure if this will work.




回答3:


Guessing you didn't have much luck with your task....

In table design, you should be able to go into properties and under Identity Specification change (Is Identity) to Yes and assign the column primary key if it formerly had the primary key.




回答4:


From SqlServerCentral.com

Changing from Non-IDENTITY to IDENTITY and vice versa




回答5:


An Identity is a property that is set at the time the table is created or a new column is added in alter table statement. You can't alter the column and set it to identity and it is impossible to have two identity columns within the same table.

Depending on the size of the table, is it possible to simply create a new table? copy over the schema of the old one and then use SET IDENTITY_INSERT ON to populate the new identity column with what you want from the old one.



来源:https://stackoverflow.com/questions/756354/how-to-change-programmatically-non-identity-column-to-identity-one

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