advanced Database Lab, Schemes and Mind Maps of Software Engineering

This document is about advanced database lab manual

Typology: Schemes and Mind Maps

2021/2022

Uploaded on 01/06/2023

TsegayeTalegngeta
TsegayeTalegngeta 🇪🇹

5 documents

1 / 82

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Prepared by TsegawKelela, Lecturer at the school of computing, Bahir Dar Institute of Technology
Bahir Dar Intistute of Technology (BiT)
Faculty of Computing
Laboratory Manual
for
Advanced Database systems
Prepared by Tsegaw Kelela (Msc.)
First released on March, 2015
Revised on November 2022
Bahir Dar University, Ethiopia
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52

Partial preview of the text

Download advanced Database Lab and more Schemes and Mind Maps Software Engineering in PDF only on Docsity!

Prepared by TsegawKelela, Lecturer at the school of computing, Bahir Dar Institute of Technology

Bahir Dar Intistute of Technology (BiT)

Faculty of Computing

Laboratory Manual

for

Advanced Database systems

Prepared by Tsegaw Kelela (Msc.)

First released on March, 2015

Revised on November 2022

Bahir Dar University, Ethiopia

i

Table of Contents

  • Introduction Acknowledgement v
    1. Laboratory session 1: Basics of T-SQL programming
    • Learning Objective:
    • 1.1. Decalring variables and Parameters:
    • 1.2. 1.2 IF ELSE statemens
    • 1.3. 1.3 WHILE Loop With CONTINUE and BREAK Keywords
    • 1.4. 1.4.CASE… When expressions
    • 1.5 Exercises
    1. Laboratory session 2: User defined functions
    • Learning objective
    • 2.1 Creating scalar user defined functions using SQL server:
    • 2.2. Inline table valued functions
    • 2.3 Multi statements table valued functions
    • 2.4. Altering Functions
    • 2.5. Dropping Functions
    • 2.6. Exercise
    • 2.7 Creating function using Oracle SQL...................................................................................
    1. Laboratory session 3: Stored Procedures
    • Learning Objective....................................................................................................................
    • 3.1 What is stored procedure?
    • 3.2. Stored Procedures vs Functions:
    • 3.3. Executing stored procedures
    • 3.4 .Droping Stored procedures
    • 3.5.Modifying stored procedures
    • 3.6 Exercise
      • Oracle syntax to create storedprocedure
    1. Laboratory Session 4: Triggers
    • Learning Objective:
    • 4.1. What is Trigger?
    • 4.2 .DML Triggers:
    • 4.3. DDL Triggers ii
    • 4.3. Dropping a Trigger
    • 4.4 Disabling and Enabling a Trigger
    • 4.5. Creating trigger using Oracle syntax:
    • 4.6 Calling Procedures within Triggers
    • 4.7. Exercise
    1. Laboratory Session 5: Configuring Server and Database security
    • Learning Objective:
    • 5.1 Creating Logins
    • 5.2 Creating and Managing database Users
    • 5.3 Creating Schemas................................................................................................................
    • 5.4. Creating Roles
    • 5.5 Granting Permissions
    • 5.6 Revoking Permissions
    • 5.7 Exercise
    1. Laboratory Session 6: Configuring oracle database Security
    • 6.1. Creating user accounts
    • 6.2 Granting permission
    • 6.3. Assigning membership to roles
    • 6.4. Granting permission
    • 6.5. Exercise
    1. Laboratory Session7: Managing Transactions
    • Learning Objective....................................................................................................................
    • What a transaction is?
    • 7.1. Transaction management modes
    • 7.2. Transaction Isolation models
    • 7.3 Exercise
    1. Laboratory Session 8: Data Import and Export
    • Learning Objective....................................................................................................................
    • 8.1. Importing from a text file
    • 8.2. Exporting to a spreadsheet
    • 8.3. Exercise
    1. Laboratory Session 9: Backup and Restore configuration
    • Learning Objective....................................................................................................................
    • Introduction iii
    • 9.2. Backing up data..................................................................................................................
    • 9.3. Restoring a backup
    • 9.4. Exercise
    1. Laboratory Session10: Replication
    • Learning Objective....................................................................................................................
    • Introduction
    • 10.1.Replication Architecture
    • 10.2.Configuring the Distributor...............................................................................................
    • 10.3.Configuring a transactional Publisher
    • 10.4. Exercise
    1. Laboratory Session 11: Database Mirroring
    • Learning Objective:
      • 11.1 Mirroring Prerequisites
      • 11.2. Endpoint Firewall Rules
      • 11.3. Database Mirroring Monitor
    • Exercise
    1. Laboratory Session 12: Log shipping
    • Learning Objective:
    • 12.1. Steps to configure log shipping........................................................................................
      • A. Using SQL Server Management Studio
      • B. Using Transact SQL
    • Exercise
  • Bibliography
  • Annexes.........................................................................................................................................
    • Annex
    • Annex

iv

List of Acronyms

DDL Data Definition Language

DML Data Manipulation Language

DBMS Database Management System

DB Database

SSMS SQL Server Management Studio

SQL Structured Query Language

SSIS SQL Server Integration Service

SSRS SQL Server Reporting Service

T-SQL Transact SQL

Introduction

The past few decades have seen a proliferation of organizations that rely heavily on information technology. These organizations store their data in databases. There are several database management systems (DBMS) available in the software world with primary differences in performance, platform support, license, security and functionalities they provide.

In this manual, Microsoft SQL server 2012 and oracle database 12c (where deemed necessary) are used for demonstrating some database concepts. The lessons covered in this manual cover advanced concepts from both database development and administration point of view.

This manual is primarily prepared for Bsc degree students who already have taken the course “Fundamentals of Database Systems” or equivalent. The manual covers advanced database topics such as functions, stored procedures, triggers, security, transaction, import/export, backup, replication, mirroring and log shipping. After explanation of each topic, examples are given. In addition, each session includes hands-on exercises to test the knowledge of students and challenge them how to apply that knowledge to solve real world practical business problems.

The database tables used in this material are taken from the hypothetical Logical data model of XYZ registrar and ABC Publishing databases which are shown in Annex 1and 2 of this manual.

To evaluate student individual practical skills and performance on this course, there will be laboratory tests seriously monitored on regular basis.

The following DBMS softwares are needed to practice the concepts covered in this material:

 Microsoft SQL Server 2012 or Later  Oracle 12c or Later

1. Laboratory session 1: Basics of T-SQL programming

Learning Objective:

At the end of this lesson, students will be able to:  Declare variables  Understand the usage of If…Else statements

 Understand the usage of WHILE Loop With CONTINUE and BREAK Keywords

 Understand the usage of CASE…WHEN expressions  Use control structures to solve problems

1.1. Decalring variables and Parameters:

In SQL Server, if a variable is typically known as a local variable, it is only available in the batch, stored procedure or code block in which it is defined. A local variable is defined using the Transact-SQL (T-SQL) DECLARE statement. The name of the local variable needs to start with the @ symbol as the first character of its name. A local variable can be declared as any system or user defined data type. Here is a typical declaration for an integer variable named @Count. DECLARE @Count INT More than one variable can be defined with a single DECLARE statement. To define multiple variables, with a single DECLARE statement, you separate each variable definition with a comma, like this: DECLARE @Count INT, @X INT, @Y INT, @Z CHAR (10) In the above declaration, 4 local variables with a single DECLARE statement. A local variable is initially assigned a NULL value. A value can be assigned to a local variable by using the SET or SELECT statement. On the SET command you specify the local variable and the value you wish to assign to the local variable. Here is an example of where I have defined my @Count variable and then initialize the variable to 1. DECLARE @Count INT SET @Count = 1 Here is an example of how to use the SELECT statement to initialize the value of a local variable with the value returned from a select that fetch the total number of rows in the employee table. DECLARE @ROWCNT INT SELECT @ROWCNT= (SELECT COUNT (*) FROM employee) One of the uses of a variable is to programmatically control the records returned from a SELECT statement. You do this by using a variable in the WHERE clause.

if (select count(*) from Sales.dbo.Customer where fname like '[A-D]%') > 0 Print 'A-D Customers are Found'

The above examples only showed how to execute a single T-SQL statement if the condition is true. T-SQL allows you to execute a block of code as well. A code block is created by using a "BEGIN" statement before the first line of code in the code block, and an "END" statement after that last line of code in the code block. Here is any example that executes a code block when the IF statement condition evaluates to true. if db_name() = 'master' begin Print 'We are in the Master Database' Print '' Print 'So whatever code you execute must be done carefully' End else if db_name() = 'Sales' begin Print 'We are in the test Sales’ database Print 'So Enjoy' End Sometimes you want to not only execute some code when you have a true condition, but also want to execute a different set of T-SQL statements when you have a false condition. If this is your requirement then you will need to use the IF...ELSE construct, that I called format two above. Example: Suppose we want to determine whether to update or add a record to the employee table in the HR database. The decision is based on whether the employee already exists in the HR.dbo.Employee table. Here is the T-SQL code to perform this existence test for two different EmployeeId's. if exists(select * from HR.dbo.Employee where CustomerId = 'Abebe123') Print 'Need to update Record 'Abebe123' else Print 'Need to add Employee Record 'Abebe123'

1.3. 1.3 WHILE Loop With CONTINUE and BREAK Keywords

The BREAK keyword will exit the while loop and control is moved to next statement after the

while loop. CONTINUE keyword skips all the statement after its execution and control is

sent to first statement of while loop.

Example 1:

WHILE (SELECT AVG(ListPrice) FROM Product) < 300

BEGIN

UPDATE Product

SET ListPrice = ListPrice * 2

IF (SELECT MAX(ListPrice) FROM Product) > 500

BREAK

ELSE

CONTINUE

END

Example 2: usage of simple while loop DECLARE @counter INT SET @counter = 1 WHILE @counter <=5) BEGIN PRINT @counter SET @counter = @counter + 1 END Example 3: Usage of WHILE Loop with BREAK keyword DECLARE @counter INT SET @counter = 1 WHILE (@counter <=5) BEGIN PRINT @counter SET @counter =@counter + 1 IF @counter = 4 BREAK; END

1.4. 1.4.CASE… When expressions

Evaluates a list of conditions and returns one of multiple possible result expressions.

The CASE expression has two formats:

The simple CASE expression : It compares an expression to a set of simple expressions to determine the result.

ELSE 'Technical Assistant' END FROM employee ORDER BY sex; GO

1.5 Exercises

  1. Use if …Else statement and write T-SQL program to convert Letter grades into their corresponding Number grades
  2. Use while… loop and write T-SQL program to find the factorial of a number
  3. Use CASE……When and classify the payment category of employees as follows: a. For salary >=10000………..High paid b. For salary >=5000………..Midium paid c. For salary <5000…………...Low paid

2. Laboratory session 2: User defined functions

Learning objective

At the end of this lab session, students will be able to:  Create and alter user defined functions  Use functions to solve problems User defined functions are functions which are developed by the users of the database system to supplement and extend the built-in functions.A user-defined function takes zero, or more, input parameters and returns either a scalar value or a table. Input parameters can be any data type except timestamp,cursor, or table. User defined functions may take the following forms: a. Scalar user defined functions b. Inline table valued functions c. Multi statements table valued functions

2.1 Creating scalar user defined functions using SQL server:

Syntax: CREATE FUNCTION [schema_name.]function_name ([@parameter_name parameter_data_type],[@parameter_name2 parameter_data_type], [@parameter_name parameter_data_type],…[parameter_nameN parameter_data_type] ) RETURNS return_data_type [ WITH<function_option>] AS BEGIN function_body RETURN scalar_expression END

Where Schema_name = the name of the function owner function_name = any valid sysname for the function @ parameter_name1 ………… @ parameter_nameN = the name of the parameter for the function return_data_type = any scalar data type data type like int, Varchar,Nvarcahr, date, char,Ncahr, etc.

 If the function is being schema-bound, you must have REERENCE permission on tables, views, and functions referenced by the function. REFERENCE permissions can be granted through the GRANT statement to views and user defined functions as well as tables.  If a CREATE TABLE or ALTER TABLE S statement references a user-defined function in a CHECK constraint, DEFAULT clause, or computed column, the table owner must also own the function.

2.2. Inline table valued functions

These type of functions are fucntions that return list of records/tables based on a logic defined using a single SQL statement. Syntax: CREATE FUNCTION [ schema_name. ] function_name ( [ { @parameter_name ] parameter_data_type [ ,...n ] ] ) RETURNS TABLE [ WITH<function_option> [ ,...n ] ] [ AS ] RETURN [ ( ] select_stmt [ ) ] [ ; ]

Example : create an inline table valued function to list the name of all female Instructors create function fn_FemaleInstructors() returns table as return select FirstName,MidleNamefrom Instructor where sex=‘F‘ To call the function, run the function in following manner: select * from dbo. fn_FemaleInstructors()

2.3 Multi statements table valued functions

These type of functions are fucntions that return list of records/tables based on a logic defined using many SQL statements that perform complex operations. In the same way that you use a view, you can usea table-valued function in the FROM clause of a Transact-SQL statement. When using a multi-statement table-valued function, consider the following facts:

 The BEGIN and END delimit the body of the function  The RETURNS clause specifies table as the data type returned.  The RETUENS clause defines a name for the table and defines the format of the table. The scope of the return variable name is local to the function.

Syntax:

CREATE FUNCTION [schema_name.] function_name ( [@parameter_name parameter_data_type, [ ,...n ] ] ) RETURNS @return_variable TABLE <table_type_definition> [ WITH<function_option> [ ,...n ] ] AS BEGIN function_body RETURN END Example : create a multi-statement table-valued function that returns the name orFull names of employees, depending on the parameter provided.

Solution:

CREATE FUNCTION fn_Employees (@length varchar(60)) RETURNS @fn_Employee TABLE (EmployeeIDint Primary Key Not Null, EmployeeName varchar(16) Not Null) AS BEGIN IF (@length =‘ShortName‘) INSERT @fn_Employees SELECT EmployeeID, fName FROM Employees ELSE IF(@length =‘FullName‘) INSERT @fn_Employees SELECT EmployeeID,fName + ‗ ‘+MidName + ‗ ‘ + GfatherName FROM Employees RETURN END

2.4. Altering Functions

You modify a user-defined function by using the ALTER FUNCTION statement Syntax: ALTER FUNCTION function_name This example shows how to alter a function ALTER FUNCTION dbo. fn_NetPay

  1. Write a scalar function that returns the average price of Books published by male authors.
  2. Write a scalar function that returns the total number of female Authors who published database books by Jimma publishers.
  3. Write a scalar function that takes ‗Publisher_Name‘ as an argument and return total number of authors who published books in the past ten years.
  4. Create an inline table valued function that generate the list of all authors who published java books
  5. Create a multi statement table valued function to find ID, name and sex of all authors who already published books. Call this function under a new scalar function that returns the total number of books published by female authors.

2.7 Creating function using Oracle SQL

Synax:

create [or replace] function [schema .] function [( argumentdatatype [, argument datatype]... )] returndatatype { is | as } { pl/sql_function_body }}; If a function already exists, you may replace it via create or replace function command. Ifyou use the or replace clause, any EXECUTE grants previously made on the function will remainin place. Example:

create or replace functionNetPay(sal float) return float is Np float; begin if (sal<=150) then Np:=sal; elsif (sal<=650) then NP:=sal-(sal-150).1; Elsif(sal>=651) then NP:=sal-(50+(sal-650).15) else NP:=sal-(112.50+(sal-1400)*.15); end if; returnNp; end;

To call the above oracle function, use the following code Select NetPay(NetPay) from dual; N.B. Dual is a dummy table with one element in it. It is useful because Oracle doesn't allow statements without specifying the From clause.

Exercise

Show oracle equivalent SQL codes for the functions we created Using SQL server codes.

Salary deduction in a given range

Salary Tax(%) 0 - 150 0 151 - 650 10 651 - 1400 15

= 1401 20