faqts : Computers : Databases : Microsoft SQL Server

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

9 of 10 people (90%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

Database: Microsoft SQL server: Table: Create: How create 2 tables,primary+foreign key, using SQL?

Dec 22nd, 2003 13:16
Knud van Eeden,


----------------------------------------------------------------------
--- Knud van Eeden --- 22 December 2003 - 10:13 pm -------------------

Database: Microsoft SQL server: Table: Create: How create 2 
tables,primary+foreign key, using SQL?

---

For example, you want to create 2 tables,
one table with person information,
and
another table with emailaddresses of this persons.

---

Steps: Overview:

---

 1. -Design your tables

      Table 1:

      ---

      Table 'Person'
      ----------------------------------------------------
      NAME                     PERSONKEY (=PRIMARY KEY)
      ----------------------------------------------------
      john doe                 1
      vanessa beau             2
      ----------------------------------------------------

      ---

      Table 2:

      ---

      Table 'Email'
      -----------------------------------------------------
      EMAILADDRESS             PERSONKEY (=FOREIGN KEY)
      -----------------------------------------------------
      john.doe@test.com        1
      j.d@aol.com              1
      johnny6@yahoo.com        1
      vanessa@vendor.com       2
      vanessa.beau@yahoo.com   2
      v.b.@aol.com             2
      -----------------------------------------------------

 2. -Create your tables

     1. Creating this table 1 in SQL

        ---

      CREATE TABLE Person (
       Name VARCHAR( 50 ) NOT NULL,
       PersonKey INT NOT NULL,
       PRIMARY KEY ( PersonKey )
      );

        ---

     2. Creating this table 2 in SQL

        ---

      CREATE TABLE Email (
       emailaddress VARCHAR( 50 ) NOT NULL,
       PersonKey INT NOT NULL,
       FOREIGN KEY ( PersonKey ) REFERENCES Person ( PersonKey )
      );

        ---

---
---

More in general:

---

 CREATE TABLE <your tablename> (
  <your columnname1> <Datatype1> [NOT NULL],
  <your columnname2> <Datatype2> [NOT NULL],
  ...
  <Columnnamelast> <Datatypelast> [NOT NULL],
  [PRIMARY KEY ( <your columnnameI> ) ]
  [FOREIGN KEY ( <your columnnameJ> ) REFERENCES <your columnnameK> ( 
<your columnnameJ> )]
 );

---
---

Internet: see also:

---

Database: Microsoft SQL server: SQL: Operation: Overview:Can you give 
an overview of SQL operations?
http://www.faqts.com/knowledge_base/view.phtml/aid/27560/fid/147

----------------------------------------------------------------------