Programmatically adding an ID field to a table in SQL Server

We usually encounter a situation where we have to dynamically generate an ID columns based on some columns. The 'Customers' table of the Northwind database does not have an ID column. Let us see how to create and populate the ID column. The data will be ordered by the Country, City and Address columns.

First add a Column 'ID' to the table Customers


ALTER TABLE Customers


ADD ID int null


GO




Now execute the following code to insert data into the ID column based on some columns.


UPDATE temp


SET ID=Rowno


FROM


(


SELECT ID, ROW_NUMBER() OVER (ORDER BY [Country] asc, [City] asc, [Address] desc) AS Rowno


FROM Customers


)temp




The query shown above inserts data into the ID column based on the Country, City and Address fields


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

No comments: