How to write a primary key constraint in SQL Server?

In SQL Server, the following syntax can be used to create a primary key constraint:

ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...)

In this example, `table_name` is the name of the table where the primary key constraint is being added, `constraint_name` is the name of the primary key constraint (optional), and `column1, column2, …` are the columns to be used as the primary key. For instance, to create a primary key constraint named `PK_Users` with the `ID` column as the primary key:

ALTER TABLE Users
ADD CONSTRAINT PK_Users PRIMARY KEY (ID)

One option to directly define a primary key constraint when creating a table is by using the following syntax:

CREATE TABLE table_name
(

    column1 datatype PRIMARY KEY,

    column2 datatype,

    … )

For example, create a table called Users with the ID column as the primary key.

CREATE TABLE Users
(

    ID int PRIMARY KEY,

    Name varchar(50),

    … )

Please note that the purpose of a primary key constraint is to ensure that a column or group of columns in a table is unique and not empty. Therefore, the values in the primary key column cannot be duplicated and cannot be NULL.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds