SQL SERVER – Add or Remove Identity Property on Column

This article contribution from one of my favorite SQL Expert Imran Mohammed. He is one man who has lots of ideas and helps people from all over the world with passion using this community as platform. His constant zeal to learn more about SQL Server keeps him engaging him to do new SQL Server related activity every time.

1. Adding Identity Property to an existing column in a table.

How difficult is it to add an Identity property to an existing column in a table? Is there any T-SQL that can perform this action?

For most, the answer to the above two questions is an absolute NO! There is no straightforward T-SQL like ALTER TABLE… or MODIFY COLUMN to add an Identity Property to an existing column in a table.

However, there is an easy way to accomplish this action. It can be done through SSMS.

Are you finding my answer difficult to believe? Let me explain.

Let’s first see what SSMS does in backend when you add Identity property on an existing column in any table.

Now, let’s create an example table for better understanding.

SQL SERVER - Add or Remove Identity Property on Column im1

This table is vacant, with no records, as you can see in the following screenshot.

SQL SERVER - Add or Remove Identity Property on Column im2

Take a look at the design of this table in SSMS.

SQL SERVER - Add or Remove Identity Property on Column im3

Now let us make eid, an Identity column.

This is very easy.  All you have to do is just select Yes from the drop down list and you are done!

SQL SERVER - Add or Remove Identity Property on Column im4

But before moving further let’s see what T-SQL SQL Server is using to make this change.

You will notice that T-SQL is used by SQL Server to make this change.

After you make the change for Identity property from No to Yes, on top in tools box, you will see Generate Change Script. This is the T-SQL Script that SQL Server will use to make this change.

SQL SERVER - Add or Remove Identity Property on Column im5

SQL SERVER - Add or Remove Identity Property on Column im6

Unfortunately, I cannot expand this dialogue box further to show you the complete script, so I have copied this script below.

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN
TRANSACTION
SET QUOTED_IDENTIFIER ON
SET
ARITHABORT ON
SET
NUMERIC_ROUNDABORT OFF
SET
CONCAT_NULL_YIELDS_NULL ON
SET
ANSI_NULLS ON
SET
ANSI_PADDING ON
SET
ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_example1
(
eid INT NOT NULL IDENTITY (1, 1)
)
ON [PRIMARY] GO
SET IDENTITY_INSERT dbo.Tmp_example1 ON
GO
IF EXISTS(SELECT * FROM dbo.example1)
EXEC('INSERT INTO dbo.Tmp_example1 (eid)
SELECT eid FROM dbo.example1 WITH (HOLDLOCK TABLOCKX)'
)
GO
SET IDENTITY_INSERT dbo.Tmp_example1 OFF
GO
DROP TABLE dbo.example1
GO
EXECUTE sp_rename N'dbo.Tmp_example1', N'example1', 'OBJECT'
GO
COMMIT

Let us understand above code in simple words:

Begin Transaction
Step 1: Create similar table structure as example1, say Tmp_Example1 with Identity Column.
Step 2: Set IDENTITY_INSERT ON on new table just created.Step 3: Insert all values from example1 to Tmp_Example1
Step 4: Set IDENTITY_INSERT OFF on Tmp_Example..
Step 5: Drop example1 (What is going on… dropping our original table???)
Step 6: Rename Tmp_Example1 to Example1.
Commit Transaction

What if you have millions and millions of records in your table?

Imagine how much time it would take to copy an entire table?

Just to make a column Identity do you really need to go through all these and take so much pain?

Certainly not!

Same is the case when you want to remove Identity column property from a column.

2. Removing Identity Property from an existing column in a table.

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET
ARITHABORT ON
SET
NUMERIC_ROUNDABORT OFF
SET
CONCAT_NULL_YIELDS_NULL ON
SET
ANSI_NULLS ON
SET
ANSI_PADDING ON
SET
ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_example1
(
eid INT NOT NULL
)
ON [PRIMARY] GO
IF EXISTS(SELECT * FROM dbo.example1)
EXEC('INSERT INTO dbo.Tmp_example1 (eid)
SELECT eid FROM dbo.example1 WITH (HOLDLOCK TABLOCKX)'
)
GO
DROP TABLE dbo.example1
GO
EXECUTE sp_rename N'dbo.Tmp_example1', N'example1', 'OBJECT'
GO
COMMIT

Once again, I would like to congratulate Imran Mohammed for this wonderful article.

Reference : Pinal Dave (https://blog.sqlauthority.com)

SQL Identity, SQL Scripts
Previous Post
SQL SERVER – Example of DDL, DML, DCL and TCL Commands
Next Post
SQL SERVER – Roadmap of Microsoft Certifications – SQL Server Certifications

Related Posts

107 Comments. Leave new

  • Brian Tkatch
    May 4, 2009 5:14 pm

    Thanx for the simple blog. Sometimes we need to go through the “simple” things to remind us of what is available.

    Reply
  • MOhammed Shakeel
    May 9, 2009 10:42 am

    First of all i would like to thank you Pinal Dave for creating this community which helps to know new things in this challenging world , and also the article written by Mr. Mohammed Imran is also very helpfull and clear to understand, which is very new and unique…

    Thanks and regards
    Md shakeel.

    Reply
  • Praveen Agrawal
    June 12, 2009 12:35 pm

    Hi pinal,

    How we can add identity in existing column of a Table.
    Like I have ID column in a table, i want to Add identity in ID column. plz reply soon.

    Thanks

    Praveen Agrawal

    Reply
    • Tanveer Sayyed
      June 4, 2013 10:56 am

      Hi pinal sir,
      SQL Server 2012 identity problem
      In my case I created a table with identity, inserted 7 records (identity 1-7) The next record I inserted it was 1002 – inserted 2 more and it was 2002 .
      I Don’t know the exact problem , It may be because of
      1) sever restart or
      2) (rollback, recovery, concurrency)
      eg;
      1
      2
      3
      4
      5
      6
      7
      1002
      1003
      1004
      2002

      plz reply soon.

      Thanks
      Tanveer Sayyed

      Reply
  • How to drop an identity property for an existing column in the table using SQL query

    Reply
  • What if you have millions and millions of records in your table?

    Imagine how much time it would take to copy an entire table?

    Just to make a column Identity do you really need to go through all these and take so much pain?

    Certainly not!

    Why so why not ?
    Mr Imran clearly explained that
    SQL server copies the entire table and then
    changes the properties in the copied version,
    delete original and then
    renames copied table

    Which means that we are going thru a lot of pain right ?

    so..

    Reply
  • “What if you have millions and millions of records in your table?

    Imagine how much time it would take to copy an entire table?

    Just to make a column Identity do you really need to go through all these and take so much pain?

    Certainly not!”

    Ok… so, how can we do it?

    Reply
  • thanks for example excellent

    Reply
  • What is the solution guys, if not through the above document process as it is painful .. You know that

    Do you have it or not? Dont leave it dangling asking us.

    Reply
  • Imran Mohammed
    March 8, 2010 11:29 am

    Hello All,

    Okay sorry for not giving complete solution. Example above shows the first half, solution to this would be to do following.

    Step1: Add a new column to existing table with Identity Identity Property ON.

    Step2: Rename/delete existing column to which you wanted to enable Identity property.

    Step3: Rename new column you just created with Identity property ON to old column name.

    That’s it, 3 simple steps and you can avoid lot of overhead.

    Let me know if any one else knows any better way of doing this…

    ~ IM.

    Reply
    • So What’s if my database is in a hosting, and the space for log file is limited, because I have a millions of records , Then when the table copy to tableTemp the log will full, please help me…

      Reply
    • Hi Imran,

      I have the doubt with the above solution.

      How can i delete my old column. I will loose the the data.

      Please go through the script below and give me any alternative.

      Create table Test (Id int, name nvarchar(50))

      insert into Test values (1, ‘ram’), (2, ‘venkat’),(3, ‘ramkoti’), (4, ‘koti’), (5, ‘lava’)

      delete from test where id = 3

      select * from test

      alter table test add ID_PK int Identity(1,1)

      select id as Old_ID, name, ID_PK as New_ID
      from test

      Now the old values and new values are different. So we can not delete the old column right and we can not rename. ???

      Reply
    • Hi Imran,

      I have the doubt with the above solution.

      How can i delete my old column. I will loose the the data.

      Please go through the script below and give me any alternative.

      Create table Test (Id int, name nvarchar(50))

      insert into Test values (1, ‘ram’), (2, ‘venkat’),(3, ‘ramkoti’), (4, ‘koti’), (5, ‘lava’)

      delete from test where id = 3

      select * from test

      alter table test add ID_PK int Identity(1,1)

      select id as Old_ID, name, ID_PK as New_ID
      from test

      Now the old values and new values are different. So we can not delete the old column right and we can not rename???

      Reply
    • sanlive08@yahoo.com
      May 18, 2015 6:49 pm

      can you Provide above steps by screenshot
      wise example on table

      Reply
  • Where is the data population step in the new solution ? is it implicit

    Reply
  • In the new solution by Imran what I observed,

    When anybody is creating a new column, certainly they want the data in the old column because it may not be ordered and have identity gaps. So they dont want to generate new values, instead old values should be dumped. (I want to make new column exactly a replica of old one)

    How do I get them, even I cannot update new column as it is an Identity.

    Any solutions …

    Reply
  • Hello Naveen,

    The statement “SET IDENTITY_INSERT dbo.Tmp_example1 OFF” changes the table to allow insert old values in identity column.
    Please let us know if this doesn’t answer your question.

    Regards,
    Pinal Dave

    Reply
  • Deepak MIttal
    March 10, 2010 4:10 pm

    Hi Pinal,

    I have a table ‘AllUsers’ with fields UserID bigint unique and UserName.

    I have appoximate 10000 records.

    now i want add IDENTITY in column ‘UserId’ of table ‘AllUsers’ by Sql query.

    Alter Table AllUsers alter column UserId ADD IDENTITY(10001,1)

    Then showing error:

    Incorrect syntax near the keyword ‘IDENTITY’.

    Please give me a solution. I am waiting for your reply.

    Thanks & Regards,

    Deepak MIttal

    Reply
    • Im having the same problem……………..
      And im using SSMS……..
      But still the same issue…
      the problem is i cant delete the column because i have set it as a foreign key in another tabel…..

      Reply
  • Hello Deepak,

    You can add identity property to an existing column only by SSMS, not by t-sql query.

    Regards,
    Pinal Dave

    Reply
  • Hello Imran / Pinal

    You mentioned above three steps to convert a column to Identity column. Thanks for that but that is not a solution, that is simply creating an Identity column with the name you wanted. What happened to all the data in the column?

    Scenario: An Integer identity column is reaching the BIGINT range and now needs to be converted to BIGINT. The table has a millions of rows in it and some rows have been deleted over time.

    The solution mentioned above will create a new Identity column thus failing on referential integrity, since just one deleted id will cause all rows after it to point to the wrong data using the identity column.

    PS.
    SET IDENTITY_INSERT tablename ON does not allow updates on the column, only inserts.

    Reply
    • K.S. Subramanian
      May 31, 2012 12:56 am

      If all you are looking for is a way to increase the size of an existing IDENTITY column from INT to BIGINT, you can do the following:
      1. Drop all constraints/indexes that depend on the column.
      2. Change the column type to bigint using the ALTER TABLE ALTER COLUMN command. Do NOT use the IDENTITY keyword as part of the command; the column already has the IDENTITY property set, and will retain it automatically.
      3. Re-create all the constraints/indexes you had dropped in step 1.

      Reply
  • Gabriel Ochoa
    March 24, 2010 1:56 am

    if i have many tables to remove the identity property, i must change on design editor one by one ???

    thnx

    Reply
  • Pinal,
    In this solution I dont think you can maintain the foreign key and other relations. Can you pls verify?

    Reply
  • Pinal & Imran,

    Thanks for this wonderful article. I was struggling to automate a few stuff in SSIS, specially with Enabling/Disabling the Identity column using T-Sql. Just one thing needs to be mentioned in Sql Server Management studio. If you don’t see the “Generate Change Script” in the toolbar. Just right click and select “Table Designer”.

    Thank you guys
    Ganesh

    Reply
  • Anuja Khambalikar
    August 17, 2010 11:44 pm

    Pinal,Imran,

    Thanks for the solution. But do you know what will be the solution when ID column is referenced as foreign key in other multiple tables?

    because in this case it wouldnt let me delete that old ID column.

    Reply
  • Saurabh Shrivastava
    August 31, 2010 12:45 pm

    Very helpful article and the method used in this is very tricky. This helped us to improve knowledge in SQL Server.

    Thanks,
    Saurabh

    Reply
    • Hello all,

      My problem related with identity filed on SQL SERVER 2000. I have a table named EmployeeMaster .It contain two fields EmpId int identity & newEmpId int . And an update trigger written for this EmployeeMaster. I want an updation on EmployeeMaster with EmpId replaced with newEmpId and the update trigger firing. So keep a log details of old Empid and new empId to another table. But EmpId is an identity column. When updation, an error message occured ‘Updation not possible on identity filed’.

      I can turn on/off identity through enterprise manager and updation possible.

      But I want this through script.

      How can I solve this issue ?

      Reply

Leave a Reply