How do i create a table with primary keys and foreign keys ?

Posted by gondar | Filed under , , , , ,

1º - lets create a simple table, with a primary key field:

create table __TableName__
(
Field_Id int
,
Name nvarchar(20
),
constraint __PK_Name__ primary key (Field_Id
),
constraint __FK_Name__ foreign key (Field_Id) references __ReferencedTable__
)

- in this example, the field "Field_Id" is a primary key in a foreign table, and for some reason, we need it to be unique at this table to,
- after add the PK, we should add the FK, in this way, we guarantee that no one can delete the row in the "__ReferencedTable__" WHEN, there is a row at this table with that "Field_Id"

2º - creating a table with 2 or more primary keys, that are from foreign tables:

create table __TableName__
(
Field_Id int,
Field2_Id int,
constraint
__PK_Name__ primary key (Field_Id,Field2_Id),
constraint
__FK_Name1__ foreign key (Field_Id) references __ReferencedTable__
,
constraint
__FK_Name2__ foreign key (Field2_Id) references __ReferencedTable2__

)

hope it helps
[[]]

Comments are closed