...Technology Simplified

Thursday, March 8, 2012

Adding a new primary key column

No comments :
In SQL SERVER, I'm working with a table, I want to write something that will create an ID column if it doesn't exist and populate it with the next highest ID.
Query ::

IF NOT EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'SampleProduct'
AND COLUMN_NAME = 'SampleProductId'
)
BEGIN
ALTER TABLE SampleProduct
ADD SampleProductId INT IDENTITY(1,1) NOT NULL
END


This will assign identity values for all existing rows, and then provide new numbers as new rows are inserted.

No comments :

Post a Comment