Home » Blog » Topic » How to remove identity in a column through query

How to remove identity in a column through query

Barry Alllen ~ Modified: April 22nd, 2016 ~ ~ 1 Minute Reading

Home Forums How to remove identity in a column through query

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #1962 Score: 0
    Barry Alllen
    Moderator
    25 pts

    I have identity enabled in id column, in the GUI it’s working, but I want to know in query how to remove identity enabled on id

    #2085 Score: 0
    Lincoln Burrows
    Moderator
    16 pts

    You cannot remove an IDENTITY specification once set. You need to remove the entire column
    • Create a new column
    • Transfer the data to the new column
    • Drop old column
    • Rename new column to the old column name

    #2098 Score: 0
    Barry Alllen
    Moderator
    25 pts

    Thanks Lincoln for your replay, can I remove identity using transact-sql

    #2100 Score: 0
    Henry Davidson
    Moderator
    31 pts
    • Create a new column
    • alter table users add newusernum int;

    • Copy values over
    • update users set newusernum=usernum;

    • Drop the old column
    • alter table users drop column usernum;

    • Rename new column to the old column name
    • EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';

    #2134 Score: 0
    Andrew Jackson
    Moderator
    1 pt

    Hope it will help you

     BEGIN TRAN
    BEGIN TRY
        EXEC sp_rename '[SomeTable].[Id]', 'OldId';
    
        ALTER TABLE [SomeTable] ADD Id int NULL
    
        EXEC ('UPDATE [SomeTable] SET Id = OldId')
    
        ALTER TABLE [SomeTable] NOCHECK CONSTRAINT ALL
    
        ALTER TABLE [SomeTable] DROP CONSTRAINT [PK_constraintName];
        ALTER TABLE [SomeTable] DROP COLUMN OldId
        ALTER TABLE [SomeTable] ALTER COLUMN [Id] INTEGER NOT NULL
        ALTER TABLE [SomeTable] ADD CONSTRAINT PK_JobInfo PRIMARY KEY (Id)
    
        ALTER TABLE [SomeTable] CHECK CONSTRAINT ALL
    
        COMMIT TRAN
    END TRY
    BEGIN CATCH
        ROLLBACK TRAN   
        SELECT ERROR_MESSAGE ()
    END CATCH
Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.