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

61

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)
Sign up to request clarification or add additional context in comments.

3 Comments

What is the name of the toolbar?
@usefulBee Table Designer
Works perfectly. Also a point to note the fields must not be nullable
42

How about this:

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID) 

1 Comment

This is good. Practicing query in sql is always challenging !
32

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

Comments

5

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

happy coding..,

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.