Friday, March 1, 2013

ADD identity to existing Table column


EX: I have a TABLE

CREATE TABLE tempdb
( recordid INT NOT NULL, NAME VARCHAR(10) NULL)
INSERT INTO tempdb VALUES ( 1, 'NICK')

Alter Table  dbo. tempdb
Add recordId  Int Identity(1, 1)
GO
----Column names in each table must be unique. Column name 'recordId' in table 'dbo.tempdb' is specified more than once.

 you cannot add the IDENTITY property to an existing column.

However, you can add a new IDENTITY column to the table:WITH similar NAME recordId1

Alter Table  dbo. tempdb
Add recordId1  Int Identity(1, 1)
GO
--THEN DROP  the old COLUMN recordId
ALTER TABLE tempdb
DROP COLUMN recordId


 rename the new COLUMN recordId1 TO recordId
sp_RENAME 'tempdb.recordid1', 'recordid' , 'COLUMN'
GO

refresh the table AND RIGHT click ON table  choose design change the physical location OF the COLUMN TO FIRST COLUMN

Thanks

No comments:

Post a Comment

https://blog.sqlauthority.com/2009/06/27/sql-server-fix-error-17892-logon-failed-for-login-due-to-trigger-execution-changed-database-context...