Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

add a primary key and foreign key

Status
Not open for further replies.

mkey

Programmer
Oct 3, 2001
288
CA
Hi all,

How can you add a primary key to an existing table?
The structure is like this:

CREATE TABLE [dbo].[TEST1] (
[ID] [int] NULL ,
[NAME] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)

Now I need to modify the test1 table so that ID column will be the Primary key? Also how can you alter the table to add the FK?
Any sample script will be of help as I don't have a sql server book.

Thanks!
 
alter table dbo.test1
add constraint test1PrimaryKey primary key(id)

alter table dbo.test2
add constraint test2ForeignKey foreign key(fkColumn)
references dbo.test1(id)
 
Hi,

Try this


alter table TEST1 alter column [id] int not null

alter table TEST1 Add constraint pkId primary key(id)

Sunil
 
By the way, if you have SQL Server you do a have a book to look this sort of thing up in. It's called Books Online and can be found by clicking the help icon in Enterprise Manager or several other ways. If you go to Programs, Microsoft SQL Server from your start menu, it should be one of the choices there too.

If you are looking for some good books, try the following FAQ:
Useful Reference Books for SQL Server Professionals
faq183-3324
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top