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

No comments:

Post a Comment