Advanced Database Systems: Lab Material (Part I)
Advanced Database Systems: Lab Material (Part I)
Lab 1: Functions
Lab 2: Stored Procedures
Lab 3: Triggers
Lab 4: Configuring Database security
Lab 5: Configuring Database security
Lab 6: Managing spatial data
Lab 7: Transactions
Lab 8: Data Import and Export
Lab 9: Backup configuration
1
Abay G.
Lab Session 1
Functions in SQL Server /Oracle
There are two categories of functions
1. Built in functions
a. SQL Server: ABS,SQRT, GETDATE(),DATEPART, CONVERT,DATEDIFF, etc….
b. Oracle: ABS, SQRT ,SYSDATE() ,COS,
2. User defined functions
a. Scalar user defined functions
b. Inline table valued functions
c. Multi statements table valued functions
go
create function netPay(@sal int)
returns float
2
Abay G.
as
begin
declare @np float
if @sal<150
set @np=@sal
else
set @[email protected]*@sal
return @np
end
go
To call the fuction, we have to prefix the funcation_name with the default schema dbo.
Example of calling the function:
select dbo.netPay(employee.salary) from employee
Example
create function emp(@id int)
returns table
as
return select * from employee where id=@id
To call the function, run the following query:
select * from dbo.emp(1)
3
Abay G.
Example
go
create function empnames(@id int)
returns @report table(fname varchar(50))
as
begin
insert @report select fname from employee where id=@id
return
end
To call the funciton, run the following query
select * from dbo.empnames(1)
Exercise
1. Create a function which gives you the maximum of two integers.
2. Suppose that we have two tables named as:
a. Student(fname, studID, sex)
b. Stud_Grade (studID, courseNo,CourseTitle, CrHr, Grade)
Based on the values that could be populated to these tables, create a function that returns the GPA of a
student when you pass studID as an argument to the function.
3. Use the following table structures taken from the Library management of Bahir
Dar University. Refer the table structures shown below and write T-SQL statements
to answer questions that follow.
Take the following assumptions:
The attribute “BookTitle ” in the book table can have values like C++, Database,
Java, etc…
The attribute “City” in the publisher table can have values like AA, Jimma,New York,
London, etc…
Book
ISB BookTitle Unit_Price PublisherID
N
Book_Author Publisher
Author
4
Abay G.
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 of 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.
If a function already exists, you may replace it via the create or replace function command. If
you use the or replace clause, any EXECUTE grants previously made on the function will remain
in place.
Example :
create or replace
function NetPay(sal float) return float
is
Np float;
begin
if (sal<=150) then
Np:=sal;
elsif (sal<=500) then
NP:=sal-(sal-150)*.1;
else
NP:=sal-(35+(sal-500)*.15);
end if;
return Np;
end;
5
Abay G.
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.
Lab Session 2
Creating Stored Procedures
A stored procedure is an SQL server routine that is compiled and saved in the database.
Speed - Stored procedures are pre-compiled, so the execution plan doesn't have to be
figured out each time they're called. This can result in a significant performance
improvement.
Code reuse and abstraction
Security - Permissions can be granted for stored procedures while being restricted for
the underlying tables. This allows the DBA to provide a method for SQL programmers
and report writers to access and/or manipulate data in a safe way.
Stored procedures are created with the CREATE PROCEDURE statement. The syntax is
shown below:
Syntax:
CREATE PROCEDURE procedure_name
@param1 (data_type,@param2 data_type @param3 data_type…………….)
AS
-- statements
Example: Based on the table shown below, write a stored procedure that can be used to
display name and IDNo of those patients who were diagnosed for Malaria . The stored
procedure takes address and sex as an argument and display IDNo and name of those patients
diagnosed for malaria
Patient
PatI Fname sex age Addres phoneNo
D s
234 Almaz F 32 B/dar 01123456
211 Hagos M 25 AA 0911435676
Treatment
PatID phyID Diagnosis
211 547 Malaria
234 678 TB
Solution :
6
Abay G.
Create procedure sp_malariaPatients(@sex varchar(6), @add varchar(15))
As
Select P.PatID,Fname from Patient p, Treatment T where P.PatID=T.PatID
and T.Diagnosis=’Malaria’
and P.sex =@sex
and P.Address=@add
Exercise
Use the table structure shown below to answer question #1 and #2
Department
DNo Dname
Student
StudID Fname Lname Sex Pocket_Money DNum
Student_Grade
StudI CourseCode Grade
D
Course
CourseCode CTitl Example:
CrHr.
e create or replace procedure removeCourse(creditHr number)
as
1. Write a declare beyond_Limit Exception; that
stored procedure increment
begin
Pocket_Money by 50% for excellent students whose GPA is above 3.75. Use
if(creditHr <=4) then
studentID as an argument to the procedure
delete from test where crHr = creditHr ;
2. Write a stored procedure that display their
else name and department of all students who
graduated with great distinction raise beyond_Limit;
a. GPA >=3.75 = Very Great Distinction
end if;
b. GPA>=3.5 = Great Distinction Exception
when byond_limit then
c. GPA>=3.5=Distinction raise_application_error(-20001,'you can not delete records with
7more than 4 credits');
end; Abay G.
/
d. GPA>=2.0 =Pass
Oracle syntax to create procedure
8
Abay G.
Lab Session 3
Creating SQL Server Triggers
We can create triggers by using the CREATE TRIGGER statement. The statement specifies
the table on which a trigger is defined, the events for which the trigger executes, and the
particular instructions for the trigger.
Syntax:
Sql statements
}
Example 1: To create a trigger that prevents modification of salary values in the employee table
we use the following code:
go
create trigger emp_update on employee
for update
as if (update(salary))
begin
Raiserror ('Slary information should not be modified',16,1)
rollback transaction
end
go
Example 2: The following code is also used to prevent deletion of more than 5 books at a time
from books table.
go
Create trigger tr_book_delete on Books for delete as
if (select count(*) from deleted ) >5
begin
Raiserror(‘You can not delete more than 5 books at once’,16,1)
Rollback transaction
end
go
9
Abay G.
Dropping a Trigger
You can remove a trigger by dropping it. Triggers are dropped automatically whenever their
associated tables are dropped.
Syntax: DROP TRIGGER trigger_name
Exercise
Student(studId,fName,sex,academic_Status)
Stud_Course (studID, courseNo,CourseTitle, CrHr)
1. Write a trigger to prevent insertion of record at a point where the total sum of Credits
taken by the student exceeds 20 credit hours.
2. Write a trigger that change the academic status of a student when the GPA is below
1.5
3. Answer question 1 based on the given schema
Suppliers
spplierCod FName Lname Se City Nationalit No_Of_Projects
e x y
Project
ProjectNo PName Budget
Product_supplier_project
Product
10
Abay G.
ProductNo Product_Nam Unit_Price Manufacturer_Nam Manufactured_Date
e e
1. Suppose that the company has a policy of limiting the number of products to which a
given supplier supplies products. Local suppliers can supply to unlimited number of
projects where as foreign suppliers should not supply products to more than three
projects. Write a trigger to enforce this policy.
2. The column “No_Of_Projects” in the suppliers table is used to count the total number
of projects for which product is supplied by each supplier. Write a trigger to adjust
this value whenever a record is added or removed from the Product_supplier_project
table.
Oracle Syntax :
11
Abay G.
Lab Session 4
Managing Server and database Security
Most Windows users need SQL Server login account to connect to SQL Server. This topic shows how
to create a SQL Server login account.
To create a SQL Server login that uses Windows Authentication using SQL Server Management
Studio (SSMS)
1. In SQL Server Management Studio, open Object Explorer and expand the folder of the server
instance in which to create the new login.
2. Right-click the Security folder, point to New, and then click Login.
3. On the General page, enter the name of a Windows user in the Login name box.
5. Click OK.
To create a SQL Server login that uses SQL Server Authentication using SSMS
1. In SQL Server Management Studio, open Object Explorer and expand the folder of the server
instance in which to create the new login.
2. Right-click the Security folder, point to New, and then click Login.
3. On the General page, enter a name for the new login in the Login name box.
4. Select SQL Server Authentication. Windows Authentication is the more secure option.
6. Select the password policy options that should be applied to the new login. In general,
enforcing password policy is the more secure option.
7. Click OK.
To create a SQL Server login that uses Windows Authentication using Transact-SQL code
12
Abay G.
In the New Query Editor, enter the following Transact-SQL command:
To create a SQL Server login that uses SQL Server Authentication using T-SQL code
1. In SQL Server Management Studio, open Object Explorer and expand the Databases folder.
3. Right-click the Security folder, point to New, and then click User.
4. On the General page, enter a name for the new user in the User name box.
5. In the Login name box, enter the name of a SQL Server login to map to the database user.
6. Click OK.
Example: Create user Mohamed for login student with default_schema =employees
13
Abay G.
CREATE SCHEMA schema_name_clause [ <schema_element> [ ...n ] ]
<schema_name_clause> ::=
{
schema_name
| AUTHORIZATION owner_name
| schema_name AUTHORIZATION owner_name
}
<schema_element> ::=
{
table_definition | view_definition | grant_statement |
revoke_statement | deny_statement
}
We can use the DROP SCHEMA schema_name statement to remove schema from the database.
However, if the schema contains objects, you can not DROP it.
Lab Session 5
Managing Server and database Security
Roles are groups that have specific access rights and permissions. These are a random set of
privileges that is granted to users.
We cannot create or change server level roles. After you create a database level role, configure the
database-level permissions of the role by using GRANT, DENY, and REVOKE.
-Users can be added to a fixed server level role using sp_addsrvrolemember stored procedure
Example: to add a login account ‘u1’ to dbcreator role, we will write the following
statement :
sp_addsrvrolemember dbcreater,u1
14
Abay G.
To add members to a database role (either fixed or user defined database roles), use the
sp_addrolemember stored procedure.
Note: if the permission is given via the [WITH GRANT OPTION],all users in the TO clause can
themselves pass on the privilege to other users.
Examples: GRANT SELECT ON student to u1
GRANT SELECT, INSERT, UPDATE (slalry) ON employee to u1
GRANT SELECT ON student to u1 WITH GRANT OPTION
GRANT CREATE TABLE TO u1 WITH GRANT OPTION
Revoke statement is used to withdraw privileges from a user without deleting that user.
Syntax:
REVOKE [ GRANT OPTION FOR ]
{
[ALL [ PRIVILEGES ] ]
|
permission [ ( column [ ,...n ] ) ] [ ,...n ]
}
[ON [ class :: ] securable ]
{TO | FROM } principal [ ,...n ]
[CASCADE] [ AS principal ]
15
Abay G.
Indicates that the ability to grant the specified permission will be revoked. This is required
when you are using the CASCADE argument. If the principal has the specified permission
without the GRANT option, the permission itself will be revoked.
class
Specifies the class of the securable on which the permission is being revoked. The scope
qualifier :: is required.
securable
Specifies the securable on which the permission is being revoked.
TO | FROM principal
Is the name of a principal. The principals from which permissions on a securable can be
revoked.
CASCADE
Indicates that the permission that is being revoked is also revoked from other principals to
which it has been granted by this principal. When you are using the CASCADE argument, you
must also include the GRANT OPTION FOR argument.
Exercise
Suppose that you are assigned to work as a database administrator (DBA) for XYZ Company.
The following sample tables and schemas are taken from the library management database of
this company.
Tables
a. Student (fname, studId,sex,department),
b. Instructor (fname, InstId,sex,Academic_Rank, salary),
c. Book (ISBN,Title, Year)
d. Book_Author (ISBN, AuthorID)
e. Author(AuthorID,fname, lname,sex)
f. Book_Borrowing(instID,ISBN,Due_DATE)
Schemas
a. Library_Members
b. Library_Resources
c. Author
1. Create three login accounts named as Aster, Tolossa and Kedir. Under the company
database, create three user accounts using the same name for login name and user
mappings (Example: for user Aster, associate it with Login name=Aster).
16
Abay G.
2. Create the student and Instructor tables under the Library_Members schema and
assign Aster as the owner of this schema
3. Under Library_Resources schema, create a view for all books of Advanced
Networking (assume that the Title column in the book table has values like Adnaced
Networking ) and assign Kedir as the owner of this schema
4. Create three roles namely student, Librarian and Instructor
5. Grant the following permissions to Librarian:
a. Select, insert and delete records on Book table under Library_Resources
schema
b. Only update the Due_DATE values in the Book_Borrowing table
c. Full control on the Author schema
6. Grant the permission to kedir to see all records on the author table. Kedir can also
grant this permission to other users.
7. Assign Aster to the member of Librarian
8. Assign Kedir to a fixed database role so that he can perform all configuration and
maintenance activities on the database and can also drop the database.
9. Add Kedir to a server role so that he can only create, alter, drop, and restore
databases.
10. Remove Tolossa from the role he has been assigned
11. Cancel all permissions given to Kedir
12. Cancel all the permissions given to Tolossa
13. Remove Aster from the role she has been assigned
B. Granting permission
Grant permissionName to username
Example: grant create session to student
Lab Session 6
Managing Transactions in SQL server
17
Abay G.
Transactions group a set of tasks into a single execution unit. Each transaction begins
with a specific task and ends when all the tasks in the group successfully complete. If
any of the tasks fail, the whole transaction fails. Therefore, a transaction has only two
results: success or failure. Incomplete steps result in the failure of the transaction.
It is the default transaction management mode of the SQL Server Database Engine. Every
Transact-SQL statement is committed or rolled back when it completes. If a statement
completes successfully, it is committed. If it encounters any error, it is rolled back. A
connection to an instance of the Database Engine operates in auto commit mode whenever this
default mode has not been overridden by either explicit or implicit transactions.
Implicit mode
Specifies any single INSERT, UPDATE,or DELETE etc… statement as a Transaction unit.
When set ON, SET IMPLICIT_TRANSACTIONS sets the connection to implicit transaction
mode. When OFF, it returns the connection to auto commit transaction mode.
Explicit mode
Generally, a group of Transact-SQL statements, where the beginning and the end of the group
are marked using statements such as BEGIN, COMMIT and ROLLBACK TRANSACTION
Users can group two or more Transact-SQL statements into a single transaction using the
following statements:
Begin Transaction
Rollback Transaction
Commit Transaction
If anything goes wrong with any of the grouped statements, all changes need to be aborted.
Syntax:
BEGIN { TRAN | TRANSACTION }
[ { transaction_name | @tran_name_variable }
[ WITH MARK [ 'description' ] ]
]
[;]
18
Abay G.
transaction_name
Is the name assigned to the transaction.Use transaction names only on the outermost
pair of nested BEGIN...COMMIT or BEGIN...ROLLBACK statements.
@tran_name_variable
Is the name of a user-defined variable containing a valid transaction name. The
variable must be declared with a char, varchar, nchar, or nvarchar data type.
Begin Commit/Rollback
Auto commit X X
Implicit X
Explicit
SQL Server offers five different transaction isolation models. Before taking a detailed look at
SQL Server's isolation models, we must first explore several of the database concurrency
issues that they try to deal with:
Dirty Reads occur when one transaction reads data written by another, uncommitted,
transaction. The danger with dirty reads is that the other transaction might never
commit, leaving the original transaction with "dirty" data.
Non-repeatable Reads occur when one transaction attempts to access the same data
twice and a second transaction modifies the data between the first transaction's read
attempts. This may cause the first transaction to read two different values for the same
data, causing the original read to be non-repeatable
Phantom Reads occur when one transaction accesses a range of data more than once
and a second transaction inserts or deletes rows that fall within that range between the
first transaction's read attempts. This can cause "phantom" rows to appear or disappear
from the first transaction's perspective.
19
Abay G.
SQL Server's isolation models each attempt to conquer a subset of these problems, providing
database administrators with a way to balance transaction isolation and business requirements.
The five SQL Server isolation models are:
The Read Committed Isolation Model is SQL Server’s default behavior. In this
model, the database does not allow transactions to read data written to a table by an
uncommitted transaction. This model protects against dirty reads, but provides no
protection against phantom reads or non-repeatable reads.
The Read Uncommitted Isolation Model offers essentially no isolation between
transactions. Any transaction can read data written by an uncommitted transaction.
This leaves the transactions vulnerable to dirty reads, phantom reads and non-
repeatable reads.
The Repeatable Read Isolation Model goes a step further than the Read Committed
model by preventing transactions from writing data that was read by another
transaction until the reading transaction completes. This isolation model protect
against both dirty reads and non-repeatable reads.
The Serializable Isolation Model uses range locks to prevent transactions from
inserting or deleting rows in a range being read by another transaction. The
Serializable model protects against all three concurrency problems.
The Snapshot Isolation Model also protects against all three concurrency problems,
but does so in a different manner. It provides each transaction with a "snapshot" of the
data it requests. The transaction may then access that snapshot for all future references,
eliminating the need to return to the source table for potentially dirty data.
If you need to change the isolation model in use by SQL Server, simply issue the following
command:
SET TRANSACTION ISOLATION LEVEL <level>
READ COMMITTED
READ UNCOMMITTED
REPEATABLE READ
SERIALIZABLE
SNAPSHOT
Example: Take the tables given below named as student and department to store student and department
information respectively.
Student
20
Abay G.
Stid Fname Dno Dnum Dname
1 Abebe 4 4 Mathematics
Department
Suppose that Mathematics department has undergone a name change to “computer science” with a value of
Dnum field =10 and a given has changed his department to computer science and assigned a new ID =100. In
order to accomplish all these changes without compromising database consistency, we need to group the
following update actions in one single transaction
The update statements to change the values for stid and Dno of the student
The update statements to change the values for Dnum and Dname of the department
CREATE PROCEDURE changeval (@oldstid int, @newstid int, @oldDnum int, @newDnum int, @oldDname
varchar(20) , @newDname varchar(20))
as
BEGIN TRANSACTION T1
Update student set stid =@newstid where stid=@oldstid
Update department set dnum =@newDnum where dnum=@oldDnum
Update department set dname =@newDname where Dname=@oldDname
If (@@error<>0)
Rollback transaction T1
Commit
Exercise
1. Take the following table structure to answer the questions that follow
ItemCod ItemName UnitPrice InitialQuantity QunatityInStoc QunatitySold
e k
387 Copmputer 9580 50 15 35
Apply the concept of transaction to properly handle the total quantity of items in stock
whenever a given set of items are sold.
2. Suppose that a bank customer has deposited money in his saving account. The information about deposit of
each customer is stored in the customers table (Accno, Fname, Lname, Balance). Write
a stored procedure to transfer money from one customer account to another. Use the concept of transaction to
effectively control the process of the transfer.
21
Abay G.