Search code examples
sqlsql-server-2005sql-server-2008indexing

How do I give a name to a primary key constraint?


I have (another) question about indexing.

I use the following code:

CREATE TABLE [dbo].[PnrDetails1](
        [OId] [int] IDENTITY(1,1) NOT NULL ,
    [file_name] [varchar](256) NOT NULL,
    [gds_id] [int] NOT NULL,
    [pnr_locator] [varchar](15) NOT NULL,
    [first_cust_name] [varchar](50) NOT NULL,
    [ticket_number] [varchar](20) NOT NULL,
    [full_price] [decimal](18, 0) NOT NULL,
    [currency_desc] [varchar](4) NOT NULL,
    [user_name] [varchar](50) NOT NULL,
    [save_time] [datetime] NOT NULL,
    [update_time] [datetime] NOT NULL,
    [clerk_id] [int] NOT NULL,
    [isUpdated] [bit] NOT NULL,
    [isDeleted] [bit] NOT NULL,
    [pnr_file_id] [int] NOT NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[PnrDetails1] ADD PRIMARY KEY CLUSTERED 
(
[OId] ASC
)ON [PRIMARY]

this is actually a script sql server 2008 created for me, but when I look at the object explorer I see an ugly name for the index (something like PK_PnrDetai_CB394B1958F2C25C). How can I change it? If so?


Solution

  • You can (and you should) explicitly give a name to your primary key constraint:

    ALTER TABLE [dbo].[PnrDetails1] 
    ADD CONSTRAINT PK_PnrDetails1
    PRIMARY KEY CLUSTERED([OId] ASC) ON [PRIMARY]
    

    You can only do this at the time of creation - so in your case, you probably have to drop it first, and then re-create it with the proper, readable name.