views:

84

answers:

2

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.

+2  A: 

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
Sam C
+1  A: 

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

priyanka.sarkar
I'd use PK_MyTable. A constraint name (PK, FK, CK, DF etc) has to be unique in sys.objects, so you can't have "PK_ID" for another table.
gbn
Right sir.. I understand my mistake. Thank you
priyanka.sarkar
I modified that
priyanka.sarkar