I have a column that I’d like to generate an ID column for. How can I do this using SQL?. Also, is it possible to specify what type of ID I’d like to have as well as length. e.g. letters+ numbers or simply numbers?.
Thank you.
I am using SQL Server and SSMS.
Advertisement
Answer
It has two ways to create primary key in SQL Server:
- First in the table like his:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, CONSTRAINT PK_Person PRIMARY KEY (ID) );
- On altering table like:
ALTER TABLE Persons ADD PRIMARY KEY (ID);
NB: Only for the number ID column, add IDENTITY(1,1) if you want the number increment automatically like:
CREATE TABLE Persons ( Personid IDENTITY(1,1) NOT NULL , PRIMARY KEY (Personid) );