Lab Session 1-3
Lab Session 1-3
Lab Session 1-3
1. Start All Programs Microsoft SQL server 2012SQL Server Management Studio.
2. Click on Connect to your default instance as shown in the following figure.
6. Leave all of the defaults and Click OK when you finished. You should now have a new
database.
Page 2 of 13
For example, to create a database with name ‘Test’, we write the following statement:
MODIFYING A DATABASE
You can modify the current settings of an existing database through the GUI or T-SQL code
To modify a database using a GUI,
For example, to modify the value of the database auto growth size, follow the next steps:
1. Right click the database
2. Click on Properties
3. Click on the Files Tab
3. Change the existing auto growth settings by modifying values as shown in Fig 1.5 below:
USE test
GO
ALTER DATABASE student MODIFY FILE (NAME = N'test', FILEGROWTH = 2048KB )
GO
Dropping a Database
We can drop a database either by right clicking the database and pressing Delete on the context
menu or using the following Drop Syntax
Page 3 of 13
Lab Session 2: CREATING, MODIFYING AND DELETING TABLES
Objective: The main objectives of this laboratory session are:
Creating Tables
Tables are a two dimensional data structure having rows and columns. They are used to store data in
the database.
Creating a table involves defining the columns with appropriate data types and specifying whether the
values to be stored in each column are allowed to be null or not.
A data type simply specifies what type of data can be placed into the object (column, variable,
parameter, and so on). Database integrity depends heavily on appropriately scoped data types. There
are four basic categories of data types in SQL server. These are Numeric, Date Time, Strings and Others.
Char[n], NChar[n], Varchar[n], Nvarchar[n] belongs to the strings data types. NChar and
Nvarcahr are Unicode String data types.
Note: n defines the string length that can be stored. For variable-length data types, max can be
specified for n, which indicates that the maximum storage size is 2 GB.
Page 4 of 13
Date and time data types
There are six data types under this category. This include Date, Datetime, smalldatetime, time(n),
datetime2(n),and datetimeOffset.
We can retrieve the list of all data types supported by the current SQL Server using the following T-SQL
Code:
Select name from sys. Types
To create a table using GUI, follow the next steps as indicated in Figure 2.1 below
1. Expand your database Right Click on Tables and specify columns with their data types
2. When you finish, go to the Tool bar and Click on Save. You will be prompted to fill the table
name. Fill in the table name box and click OK.
3. After refreshing the Tables folder, you should see the newly created table
T- SQL Syntax:
USE database_name
CREATE TABLE table_name
(
Column_Name data type NOT NULL,Column2 data type ,Column3 data type NOT
NULL...... Column N data type)
Page 5 of 13
Note:-
We can define up to 1024 columns per table.
If you do not specify NULL or NOT NULL, SQL Server provides the NULL.
USE Registrar
CREATE TABLE student
(
stud_ID int not null,
First_Name varchar(30),
Address varchar (30) default ‘Addis Ababa’
)
Modifying a table
You can modify the table by adding a new column and deleting a column from the table.
Adding a Column
The type of information that you specify when you add a column is similar to that which you supply
when you create a table.
For example, to add the column age in the student table we write :
Deleting a Column
Deleting columns are unrecoverable. Therefore, be certain that you want to remove a column before
doing so.
Page 6 of 13
Generating Column Values using Identity Property
You can use the Identity property to create columns (referred to as identity columns) that contains
system generated sequential values identifying each row Inserted into a table.
(
Column_name data type IDENTTY (seed, increment) NOT NULL
)
The following example is used to create auto increment column on the EmpID column of
Employee table with a seed valued of 1(initial value) and incrementing by 1.
Create table Employee
(EmpID int NOT NULL identity(1,1), EmpName varchar (20) )
Consider the following requirements for using the Identity property
Only one identity column is allowed per table
It must be used with integer (int, bigint, smallint, or tinyint), numric, or decimal data ypes.
The numeric and decimal data types must be specified with a scale of 0
It cannot be updated
It does not allow null values
Deleting a Table
Deleting a table removes that table definition and all data, as well as the permission for that
table. Before you delete a table, you should remove any dependencies between the table and
other objects.
Exercise
1. Create table whose name is Staff with attributes like name, Id, sex, salary, Nationality and
age (Using GUI and T-SQL code as we have seen in this lesson).
3. Modify the Staff table by modifying the data type of the age column to int.
Page 7 of 13
Lab Session 3: INSERTING DATA
Inserting Data to a table
You can insert data to a table using the GUI or T-SQL code. For example, to insert data into the course
table found under test database, use the steps shown below:
Syntax
INSERT INTO table_name[ColumnNameList] VALUES (list_of_values)
Page 8 of 13
Example: To insert values in the course table with a value of Cno=3,Ctitle=’Database’,CrHr=5
and Dno=10:
Insert into Course values(3,’Database’,5,10)
Inserting data Using INSERT ...ELECT Method .
o To insert data using this method, the columns derived from the result of the select
stamen must fit to the columns of the table we are going to insert.
Example:
Insert into Employee Select * from Instructor
Note: if ColumnNameList is not specified, the values clause expect the whole list of values
to all columns of the table.
Inserting data Using INSERT...EXEC UTE method
o This is a method of populating data to a table using the result of rows fetched by a
stored procedure
Example: To insert data to an employee table using rows fetched by A stored procedure
called fetchInstructors, we can use the following code:
Insert into Employee EXECUTE fetchInstructors
Inserting data using SELECT… INTO method
o Syntax:
Select {Column List|* } from TableName into NewTable [WHERE]
[CONDITION]
This method fetch subset of rows from an existing table and insert the rows into a
dynamically created a new table
Example: To insert rows fetched from Instructor table by creating a into a new table
table called Employee we can use the following code:
Select * from instructor into Employee
Inserting Data by Using Column Defaults.
To insert a default value on the default column of a table, we can either remove that column
from the ColumnList in the INSERT …..VALUES statement or we can use the key word
DEFAULT in place of the value.
Example: To insert the default value BahirDar into a city Column of Employee
Exercise
o Create an Emplyee table under a database called ‘HR’
Employee
IDNo Fname Lname Sex Date_of_birth Kebele Marital_status
The next example retrieves the InstID, name and fatherName from the Instructor table in which
their salary is less than 5000 birr.
Select InstID, name ,fatherName from Instructor where salary<5000
[^] Any single character not within the specified range or set
Page 11 of 13
Examples
Expression Returns
LIKE ‘[S-V] ing’ Every four letter name ending with ing and beginning with single letter from S to V
LIKE ‘M[^c]%’ Every name beginning with the letter M that does not have
Microsoft SQL Server evaluates the NOT operator first, followed by the AND operator and
then the OR operator. The Precedence order is from left to right if all operators in an
expression are of the same level.
EXAMPLE1
SELECT name, fatherName FROM Student
WHERE
sex <>’ F’ AND AcademicStatus <> 'Good'
OR
sex <>’ F’ AND dno <> 10
EXAMPLE 2
SELECT name, fatherName FROM Student
WHERE
(sex <>’ F’ AND AcademicStatus <> 'Good')
OR
(sex <>’ F’ AND dno <> 10)
EXAMPLE 3
SELECT name, fatherName FROM Student
WHERE
(sex <>’ F’ AND AcademicStatus <> 'Good')
AND
Page 12 of 13
(sex <>’ F’ AND dno <> 10)
When you use the IN search condition, use either the IN search condition or a series of
comparison expressions that are connected with an OR operator.
Example:
List the name of Instructors in department 5 or department 10
USE Registrar
SELECT name, fatherName FROM Instructor Dno IN (5, 10)
Use the IS NULL search condition to retrieve rows in which information is missing from a
specified column.
Use the IS NOT NULL search condition to retrieve rows that have known values in the specified
columns.
Exercises
1. List the name of female students
2. List all students in department 20
3. List the name of female students in department 20
4. List name and department of female students whose academic status is Passs
5. List name, id and department of male students except Asmare and Sisay
6. List name, sex and age of all students whose fname starts with ‘A’ and ends with ‘ew’
7. Show the name of instructors whose salary lies within the range of 10 and 15 thousands
8. Show all students whose academic status is not yet determined
Page 13 of 13