Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab Session 1-3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Lab Session 1: INTRODUCING MICROSOFT SQL SERVER 2012 ENVIRONMENT AND

CREATING, MODIFYING AND DELETING DATABASES

A. INTRODUCING MICROSOFT SQL SERVER 2012 ENVIRONMENT


 SQL Server Management Studio(SSMS)
You can use SQL server management studio to manage database objects using
graphical user interface, GUI (Without writing SQL codes)

To open SQL SSMS, use the following steps:

1. Start  All Programs  Microsoft SQL server 2012SQL Server Management Studio.
2. Click on Connect to your default instance as shown in the following figure.

Fig 1.1: connecting to SQL server

 SQL Server Configuration Manager (SSCM)


It is used to set or change the values of configuration settings that apply to the
database engine instance, agent service and other SQL server services
installed on the host computer.
To open SQL SSCM, use the following steps:
1. Start  All Programs  Microsoft SQL server 2012Configuration Tools  SQL
Server Configuration Manager.

Fig 1.2: connecting to SQL server


2. Right click on the service and click on properties to change the currently configured
values
 Query Editor
Page 1 of 13
You can open and use Query editor window to write Transact –SQL codes (T-SQL codes) for the
purpose of creating, maintaining and removal of server and database objects

Fig 1.3: Opening Query editor window


B. CREATING, MODIFYING AND DELETING DATABASES
 CREATING A DATABASE
C. using the graphic interface
1. Start SQL Server Management Studio by selecting Start Programs  Microsoft SQL
server 2012 Management Studio.
2. Click on Connect to your default instance of SQL Server as in Figure 1.1
3. Expand your Databases folder.
4. Right-click either the Databases folder in the console tree or the white space in the
right pane, and choose New Database from the context menu.
5. You should now see the General tab of the Database properties sheet. Enter the
database name, and leave the owner as <default>.

Fig 1.4: connecting to SQL server

6. Leave all of the defaults and Click OK when you finished. You should now have a new
database.

B. Using Transact SQL statements (T-SQL)


We can create a new database and the files used to store the database using T- SQL Code. From the
toolbar, click on New Query
Write the database creation statement on the editor and click on Execute .
Here is the simplest syntax leaving other parameters to take the default values:

CREATE DATABASE database_name


database_name Is the name of the new database. Database names must be unique within an instance
of SQL Server

Page 2 of 13
For example, to create a database with name ‘Test’, we write the following statement:

CREATE DATABASE test

 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:

Fig 1.5 modifying a database


Alternatively, you can also use T-SQL code to achieve the same result. For example, we can
modify the file growth of a test database as follows:

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

DROP DATABASE <databaseName>


Example: DROP DATABASE test
EXERCISES
1. Create a database with your Name
2. Modify the initial size of the database to be 5 MB
3. Delete the database that you have already created.

Page 3 of 13
Lab Session 2: CREATING, MODIFYING AND DELETING TABLES
Objective: The main objectives of this laboratory session are:

 To create a table and data types in SQL server


 Defining the data types for the table
 Deleting records ,dropping, altering tables

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.

Numeric data types


The numeric data type has two subcategories: exact and approximate. Exact data types fit within
a finite range of numbers. Table 2-1 lists and defines each exact numeric data type.
Data Type Range Storage
Bigint –9,223,372,036,854,775,808 to 8 bytes
9,223,372,036,854,775,807
Int –2,147,483,648 to 2,147,483,647 4 bytes
smallint –32,768 to 32,767 2 bytes
Tinyint 0 to 255 1 byte
Money –922,337,203,685,477.5808 to 8 bytes
922,337,203,685,477.5807
smallmoney –214,748.3648 to 214,748.3647 4 bytes
Table 2.1: Exact numeric data type

String data types


The string data type contains three subcategories: character, Unicode, and binary. Each contains
three specific data types. These data types are similar in that each subcategory contains a fixed-
length data type and a variable-length data type.

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

Figure 2.1 Creating a Table

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.

Example: To create the student table under a database called Registrar,

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.

Syntax: ALTER TABLE table_name ADD column_name data type

For example, to add the column age in the student table we write :

ALTER TABLE STUDENT ADD age INT

If we need to modify (change) the data type of the already created

Column, we can use the following syntax:

ALTER TABLE table_name ALTER COLUMN column_name new_data_type


For example, to change the data type of stud_ID column in the student table from integer to character
data type, we write:

ALTER TABLE student ALTER COLUMN stud_ID varchar(30)

Deleting a Column
Deleting columns are unrecoverable. Therefore, be certain that you want to remove a column before
doing so.

Syntax: ALTER TABLE table_name DROP COLUMN column_name

This example deletes a column from a table


ALTER TABLE student DROP COLUMN age

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.

Syntax: CREATE TABLE table_name

(
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.

Syntax: DROP TABLE table_name


Example: DROP TABLE student

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).

2. Modify the employee table by adding a column named Qualification.

3. Modify the Staff table by modifying the data type of the age column to int.

4. Delete the table Staff

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:

1. Navigate to Database Test TablesCourse Table

Fig 3.1 Navigating to a specific table of the database

2. Right Click on Course Table Edit Top 200 rows


3. Fill the data on each mandatory cells and press Tab at the end of each row
4. When you finish entering data, click on Execute icon on the tool bar or press F5 to save rows.

Fig 3.2 Inserting data using GUI

Inserting data using T-Code


 Inserting data Using INSERT...VALUES method
Use the INSERT statement with the VALUES clause to add rows to a table.
When you insert rows, consider the following facts and guidelines:
 Must adhere to the same order and data type of the columns in the table. Otherwise,
the insertion will fail.
 Use the column_list to specify columns that will store each incoming value.
 You must enclose the column_list in parentheses and delimit it by commas.
 If you are supplying values for all columns, using the column_list is optional
 Character data and dates must be enclosed in single quotation marks.

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

Insert into Employee(IdNo,fName,Lname,sex) values(1,’Hailu’,’Kassa’,’M’)


OR
Insert into Employee values(1,’Hailu’,’Kassa’,’M’,DEFAULT)

Exercise
o Create an Emplyee table under a database called ‘HR’
Employee
IDNo Fname Lname Sex Date_of_birth Kebele Marital_status

1 Almaz Kassa F 2/3/1977 15 Single

2 Mohamed Kemal M 4/6/1983 20 Married

3 Aynalem Molla F 12/9/1971 9 Married

4 Sisay Tesfaye M 5/10/1988 7 Single

Additional information (Assumption about existing business rules):


 Values for sex attribute are optional while Values for kebele are mandatory(it is not
possible to leave this value blank)
 The values for IDNo field could be generated automatically
Page 9 of 13
 “Married” can be used as a default value for Marital_status coulumn
2. Insert the sample data using the insertion methods we have seen in this session

Lab Session 4: RETRIEVING AND FILTERING DATA

4.1 RETRIEVING DATA BY USING THE SELECT STATEMENT


You can use the SELECT statement to specify the columns and rows of data that you want to
retrieve from tables.
Syntax: SELECT [ALL|DISTINCT]<select_list>
FROM {<table_source >}
WHERE <search_condition>
o The SELECT statement lists the items or column names, computed values, the
aggregate functions, etc to be retrieved.
o The FROM clause specifies the table or tables from which columns and rows are
returned.
o The WHERE clause specifies the condition restricting the query. You can restrict
the number of rows by using comparison operators, character strings, and logical
operators as search conditions.
When you specify columns to retrieve, consider the following facts and guidelines:
o The select list retrieves and displays the columns in the specified order
o Separate the column names with commas, except for the last column name
o Avoid or minimize the use of an asterisk(*) in the select list. An asterisk is used to
retrieve all columns from a table.
Example: The next statement retrieves the Fname, Lname and sex columns of
all instructors from the instructor table.
Select Fname, Lname,sex from Instructor

Selecting ALL Columns (SELECT *)


Asterisk * is used to get all the columns of a particular table. For example the SQL select * from
Employee will retrieve the entire records of the employee table.
SELECT * FROM Employee

Eliminating Duplicate Rows using Distinct


To eliminate the duplicates from the result ser we use the key word DISTINCT.
Example: SELECT DISTINCT cno from student_course

Using the WHERE Clause to Specify Rows


Using the WHERE clause, you can retrieve specific rows based on given search conditions. The
search conditions in the WHERE clause can obtain an unlimited list of predicates.
Syntax:
<search_condition> uses expression {=|<>|>|>=|<|<=}expression
String expressions [NOT]LIKE string_expression
Expressions [NOT |BETWEEN]expression AND expression
When you specify rows with the WHERE clause, consider the following facts and guidelines:
Page 10 of 13
o Place single quotation marks around all char, nchar,varchar,nvarchar, text, datetime,
and smalldatetime data
o Use a WHERE clause to limit the number of rows that are returned.

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

4.2 FILTERING DATA


You can limit the results by specifying search conditions in a WHERE clause to filter data. There
is no limit to the number of search conditions that you can include in a SELECT statement. The
following table describes the type of filter and the corresponding search condition that you can
use to filter data.
Type of filter Search Condition
Type of Filter Search Condition

Comparison Operators =, <, >, >=, <=, and <>

String comparisons LIKE , NOT LIKE

Logical Operators: combination of conditions AND, OR

Logical Operators: negations NOT

Range of values BETWEEN , NOT BETWEEN

List of values IN , NOT IN

Unknown values IS NULL, IS NOT NULL

Using String Comparison


You can use the LIKE search condition in combinations with wildcard characters to select rows
by comparing character strings. When you use the LIKE search condition, consider the following
facts:
o All characters in the pattern string are significant, including leading and trailing blank
spaces
o Like can be use only with data of the char, nchar, varchar, nvarchar,binary,
varbinary,smalldatetime or datetime data types, and under certain conditions, with text,
ntext, and image data types
Wildcard Description

% Any string of zeros or more characters

underscore ( _) Any single character

[] Any Single character within the specified ranges or set

[^] Any single character not within the specified range or set

Page 11 of 13
Examples
Expression Returns

LIKE ‘Br%’ Every name beginning with the letters BR

LIKE ‘%een’ Every name containg the letters en

LIKE ‘_en’ Every three letter name ending in the letters en

LIKE ‘[CK]%’ Every name beginning with the letter C or K

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

Logical and grouping operators (Parenthesis)


Use the logical operators AND, OR, and NOT to combine a series of expressions and to refine
query processing. The results of a query may vary depending on the grouping of expressions and
the order of the search conditions.
When you use logical operators:
 Use the AND operator to retrieve rows that meet all of the search criteria
 Use the OR operator to retrieve rows that meet any of the search criteria
 Use the NOT operator to negate the expressions that follows the operator.

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)

Using List of Values as Search Criteria


Use the IN search condition in the where clause to retrieve rows that match a specified list of
values.

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)

Retrieving Unknown Values


A column has a null value if no value is entered during data entry and no default values are
defined for that column. A null value is not the same as entries with a zero (a numerical value) or
a blank (a character value)

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.

Example: List all curricula that are not yet approved.


USE Registrar
SELECT * from Curriculum where appovedDate IS NULL

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

You might also like