36

How to add composite primary keys in SQL Server 2008?

I have a table as follows.

testRequest (wardNo nchar(5)
            , BHTNo nchar(5)
            , testID nchar(5)
            , reqDateTime datetime);

I need wardNo, BHTNo and testID to be a composite primary key.

How can I do this in SQL Server Management Studio?

1

4 Answers 4

60

If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.

enter image description here

Command for this is,

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID)
3
  • What is the name of the toolbar?
    – usefulBee
    Commented Apr 6, 2017 at 19:00
  • @usefulBee Table Designer Commented Oct 23, 2018 at 17:58
  • 1
    Works perfectly. Also a point to note the fields must not be nullable Commented Sep 27, 2022 at 7:39
40

How about this:

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID) 
1
  • 1
    This is good. Practicing query in sql is always challenging !
    – Sakthivel
    Commented Sep 20, 2013 at 7:35
30

How about something like

CREATE TABLE testRequest (
        wardNo nchar(5),
        BHTNo nchar(5),
        testID nchar(5),
        reqDateTime datetime,
        PRIMARY KEY (wardNo, BHTNo, testID)
);

Have a look at this example

SQL Fiddle DEMO

0
5

it simple, select columns want to insert primary key and click on Key icon on header and save tablesql composite key

happy coding..,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.