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 2012 Forums
 Transact-SQL (2012)
 add column with increasing integer values

Author  Topic 

landau66
Yak Posting Veteran

61 Posts

Posted - 2013-09-17 : 11:29:08
hi everyone!

how do i add a column to a table which i want to use as identity-column. therefor this new column should be populated with increasing integer values (1,2,3,4,5,....).

the used PK constraint i have dropped already.

many thanks to the Team
landau

sigmas
Posting Yak Master

172 Posts

Posted - 2013-09-17 : 11:37:34
alter table table_name
add column_name int not null identity(1,1)
constraint constraint_name primary key;
Go to Top of Page

landau66
Yak Posting Veteran

61 Posts

Posted - 2013-09-17 : 12:42:32
what if i want the already existing table to be in a certain order?
Acctually it is a table with a date column which used to be the PK before. Now i need a ID-column.
How can i assure that ID is in the same order like the date-column (ascending or descending does not matter)?

many thanks for the first answer already. it was very helpful

greetings from
landau
Go to Top of Page

sigmas
Posting Yak Master

172 Posts

Posted - 2013-09-17 : 14:49:05
first add a column with integer data type accept null. then execute following query

update d
set identity_column = rnk
from (select row_number() over(order by date_column) as rnk, * from table_name)d;

at last set identity property for identity_column by graphical tools of SQL Server Management Studio.
Go to Top of Page
   

- Advertisement -