Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Add Identity

Author  Topic 

mahesh_bote
Constraint Violating Yak Guru

298 Posts

Posted - 2008-01-14 : 09:53:36
Hi All,

I have one table with Roll as Primary Key. Let say Table structure is:

Roll Name Std
1 AAA 10
2 BBB 10
3 CCC 10
...

Now I have to add Identity to the table. I am not getting the right syntax for altering it.

Can anybody help me out? Rather, can anybody tell me, how to use it with ALTER TABLE?

Thanks in advance,

Mahesh

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-01-14 : 10:10:22
I dont think you have a direct way of doing this.Follow this steps:-

1) Rename the existing table and any constraints it may have.
2) Run a CREATE TABLE statement with the new definition of the column,
including constraints for the table.
3) Isssue SET IDENTITY_INSERT ON for the table to permit inserting of
explicit values in the IDENTITY column.
4) INSERT newtbl (...) SELECT ... FROM oldtbl.
5) Move referencing foreign keys to refer to the new table.
6) Restore triggers and indexes on the new table.
7) drop the old table
8) SET IDENTITY_INSERT back to OFF
5.
Go to Top of Page

jhocutt
Constraint Violating Yak Guru

385 Posts

Posted - 2008-01-14 : 10:11:28
create table #tmp (Roll int, Name varchar(10), Std int)
go
insert into #tmp
select 1 , 'AAA', 10 union all
select 2 , 'BBB', 10 union all
select 3 , 'CCC', 10
go
select * from #tmp
go
alter table #tmp add mypk int identity(1,1)
go
select * from #tmp
go
drop table #tmp
go




"God does not play dice" -- Albert Einstein
"Not only does God play dice, but he sometimes throws them where they cannot be seen."
-- Stephen Hawking
Go to Top of Page
   

- Advertisement -