Thursday, July 19, 2012

SQL Server: update column with sequential value

I have a database table that has a lot of data already in the table and I need to add a new column to this table to include a new sequential number.  In addition to adding the column I also need to populate the existing records with an incremental counter.


So I can do this by doing the following:


// adds new columns
ALTER TABLE [dbo].[d_expedientes] ADD [type_expediente] [int] default 0;


// set the value of the new column to 1,2,3,4,5,...

DECLARE @type_expediente INT 
SET @type_expediente = 0 
UPDATE d_expedientes
SET @type_expediente = type_expediente = @type_expediente + 1 


Reference:
http://www.mssqltips.com/sqlservertip/1467/populate-a-sql-server-column-with-a-sequential-number-not-using-an-identity/

No comments: