In previous articles I explained Create Identity Column or Auto increment column in SQL Server, Reset identity column in SQL Server, insert values in identity column in SQL Server, SQL Query to get month wise, year wise data and many articles relating to SQL Server, jQuery, JavaScript. Now I will explain how to add identity property to existing column in table using SQL Server 2008.
CREATE TABLE UserDtls
(
UserId int PRIMARY KEY,
UserName varchar(120),
Qualification varchar(50)
)
|
INSERT INTO UserDtls(UserId,UserName,Qualification) VALUES(1,'Suresh','B.Tech')
INSERT INTO UserDtls(UserId,UserName,Qualification) VALUES(2,'Rohini','MSC')
INSERT INTO UserDtls(UserId,UserName,Qualification) VALUES(3,'Mahendra','CA')
|
---- Create
New Table with Identity Column ------
CREATE TABLE temp1
(
UserId INT PRIMARY KEY IDENTITY,
UserName VARCHAR(120),
Qualification VARCHAR(50)
)
----Insert
Data into newly created table----------
SET IDENTITY_INSERT temp1 ON
IF EXISTS(SELECT TOP 1 * FROM UserDtls)
BEGIN
INSERT INTO temp1(UserId,UserName,Qualification)
SELECT
UserId,UserName,Qualification
FROM UserDtls
END
SET IDENTITY_INSERT temp1 OFF
--------Once
Data moved to new table drop old table --------
DROP TABLE UserDtls
-------Finally
rename new table name to old table name
EXEC sp_rename 'temp1','UserDtls'
|
|
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
Subscribe by RSS
Subscribe by Email
|
|||
|
|

Subscribe by RSS
Subscribe by Email
0 comments :