Interview Questions and Answers
How to Add and Remove Identity Column from Existing Table?
How to remove IDENTITY from a Column of a SQL Server?
The one line answer is – There is no specific way for disabling the IDENTITY on a Table Column.
The one line answer is – There is no specific way for disabling the IDENTITY on a Table Column.
There are few hacky ways to do this so let me share here.
Option 1:
- Create a replica blank table without any constraint
- Transfer all data from your main table to replica table
- Apply proper constraints like a Primary key or Unique key on that column which is identity column of the main table
- Dropped the main table
- Rename your replica table to the original table name
Option 2:
- Create a replica column in the same table
- Update new column by a value of IDENTITY Column
- Check the reference of IDENTITY Column and If any then remove temporary
- Drop the IDENTITY Column
- Rename the replica column to the original column name
Ref: https://www.dbrnd.com/2018/03/sql-server-how-to-remove-identity-from-a-column/
How to set IDENTITY to existing column of a Table?
Actually, there is no any specific option for setting IDENTITY to existing Column of a Table.
But there are different tricks to do this, sharing one of the tricks here…
Create a sample table without identity column:
1
2
3
4
5
|
CREATE TABLE tbl_TestIdentity (ID INT, Name VARCHAR(10))
INSERT INTO tbl_TestIdentity VALUES
(1,'ABC'), (2,'XYZ'),(3,'PQR')
,(4,'WER'),(5,'JKL'),(6,'ZXC')
|
Check the data:
1
2
3
4
5
6
7
8
9
10
|
SELECT *from tbl_TestIdentity
ID Name
----------- ----------
1 ABC
2 XYZ
3 PQR
4 WER
5 JKL
6 ZXC
|
Add new IDENTITY Column to table:
1
|
ALTER TABLE tbl_TestIdentity ADD ID2 INT IDENTITY (1,1);
|
Drop old ID Column:
1
|
ALTER TABLE tbl_TestIdentity DROP COLUMN ID
|
Rename new column to old column name:
1
|
Exec sp_rename 'tbl_TestIdentity.ID2', 'ID', 'Column'
|
Result:
1
2
3
4
5
6
7
8
9
10
|
SELECT *from tbl_TestIdentity
Name ID
---------- -----------
ABC 1
XYZ 2
PQR 3
WER 4
JKL 5
ZXC 6
|
Post a Comment
0 Comments