SQLTeam.com | Weblogs | Forums

Problems linking 2 tables together


#1

I'm a student at ITT Tech, in a database class currently and having a hard time with the syntax;
to add a primary key and a foreign key seems unnecessarily difficult in Microsoft SQL management studio


#2

Not really. The dbms can't think at all, so you have so specify everything about key relationships to SQL Server.

Btw, you should learn to use the SQL commands and not the gui/SSMS to define keys. Then just walk thru each part of the definition until you (basically) understand it. Don't panic, it will take some time before you truly understand it.

To add a primary key to a table:

ALTER TABLE dbo.table_name 
    ADD CONSTRAINT PK_table_name 
    PRIMARY KEY CLUSTERED ( column_name ) ON [PRIMARY];

To add a foreign key:

ALTER TABLE dbo.table_name 
    ADD CONSTRAINT FK_table_name_to_table2_name 
    FOREIGN KEY ( column_name )
    REFERENCES dbo.table2_name ( column2_name)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION