Specify PK name during table creation
-
08-07-2019 - |
Question
In MSSQL is there a way to specify a name for a PK constraint so that MSSQL doesn't provide a randomly generated PK name like so:
PK__Addresse__3214EC074E88ABD4
The only way I can see to do it now is to first create the table and then issue an ALTER command to rename the PK. It would be easier if I could do it in one shot.
Solution
Yes. Here's the syntax which SSMS generates:
CREATE TABLE [Address] (
[ID] [int] IDENTITY(1,1) NOT NULL,
<< columns here >>,
CONSTRAINT [PK_Address] PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
OTHER TIPS
At the time of table creation
CREATE TABLE MyTable
(
Id INT NOT NULL
CONSTRAINT PK_MyTable PRIMARY KEY (Id)
)
If you need to alter the table and add a Primary Constraint
ALTER TABLE MyTable
ADD CONSTRAINT PK_MyTable PRIMARY KEY (Id)
Hope this helps
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow