Creating and Working with Tables in sql server ~ MiTechDev.com

Tuesday, 7 March 2017

Creating and Working with Tables in sql server

01:57:00 Posted by raviteja swayampu , No comments
The aim of this article is to create tables with names tblPerson and tblGender and implement  primary key and foreign key constraints on columns of the two tables. In SQL Server, tables can be created graphically in two ways.This tutorials tell us how to create and work with tables.
1.Using SQL Server Management Studio (SSMS) or
2.Using a query(Sql query).

tblGender

tblPerson
To create tblPerson table, graphically, using SQL Server Management Studio
1. Right click on Tables folder in Object explorer window
2. Select New Table
3. Fill Column Name, Data Type and Allow Nulls, as shown below and save the table as tblPerson.

The following statement creates tblGender table, with ID and Gender columns. The following statement creates tblGender table, with ID and Gender columns. ID column, is the primary key column. The primary key is used to uniquely identify each row in a table. Primary key does not allow nulls.
Create Table tblGender
(ID int Not Null Primary Key,
Gender nvarchar(50))
In tblPerson table, GenderID is the foreign key referencing ID column in tblGender table. Foreign key references can be added graphically using SSMS or using a query.

To graphically add a foreign key reference
  • Right click tblPerson table and select Design
  • In the table design window, right click on GenderId column and select Relationships
  • In the Foreign Key Relationships window, click Add button
  • Now expand, in Tables and Column Specification row, by clicking the, + sign
  • Click on the elipses button, that is present in Tables and Column Specification row
  • From the Primary Key Table, dropdownlist, select tblGender
  • Click on the row below, and select ID column
  • From the column on the right hand side, select GenderId
  • Click OK and then click close.
  • Finally save the table.
Using query:
Alter table tblPerson 
add constraint tblPerson_GenderId_FK FOREIGN KEY (GenderId) references tblGender(ID)
Note: Generally we add foreign key to table column using ALTER command.
Alter table ForeignKeyTable add constraint ForeignKeyTable_ForiegnKeyColumn_FK 
FOREIGN KEY (ForiegnKeyColumn) references PrimaryKeyTable (PrimaryKeyColumn)

Foreign keys are used to enforce database integrity. In layman's terms, A foreign key in one table points to a primary key in another table. The foreign key constraint prevents invalid data form being inserted into the foreign key column. The values that you enter into the foreign key column, has to be one of the values contained in the table it points to.

0 comments:

Post a Comment