Upload
sahan-harinda-nagodawithana
View
218
Download
0
Embed Size (px)
Citation preview
7/28/2019 Lecture 5hjjkujku
1/36
Database ManagementSystems II
Lecture 5
7/28/2019 Lecture 5hjjkujku
2/36
Last Lecture Relational Algebra
SQL (DDL, DML, SELECT)
Any questions?
7/28/2019 Lecture 5hjjkujku
3/36
This lecture Views
SQL extensions (specifically T-SQL)
Transaction Basics
Triggers
Stored Procedures
7/28/2019 Lecture 5hjjkujku
4/36
ViewsAviewis a virtual table
A view is based on base tables ordefining tables
In SQL, CREATE VIEW statement isused to define views
7/28/2019 Lecture 5hjjkujku
5/36
Views (contd.)Example
Create a view of student names & their majoring
department
CREATE VIEW STUD_MAJAS
SELECT S.Name, D.NameFROM STUDENT S INNER JOINDEPARTMENT D ON(S.Major = D.DeptID)
7/28/2019 Lecture 5hjjkujku
6/36
Views (contd.)Another example
View of departments and their average salary
CREATE VIEW DEPT_SAL (Dept, AvgSalary)ASSELECT D.Name, AVG(E.Salary)
FROM EMPLOYEE E INNER JOINDEPARTMENT D ON(E.Dept = D.DeptID)
GROUP BY D.Name
7/28/2019 Lecture 5hjjkujku
7/36
Views (contd.) Now, we can query the view similar to a
table
Example..
List the departments with average salary >
30,000SELECT Dept
FROM DEPT_SAL
WHERE AvgSalary > 30,000
7/28/2019 Lecture 5hjjkujku
8/36
Views (contd.) Dropping a view...
DROP VIEW DEPT_SAL
7/28/2019 Lecture 5hjjkujku
9/36
Views (contd.) Updating a view can be ambiguous
Views containing aggregate functions are not
updateable
Example
UPDATE DEPT_SAL
SET AvgSalary = 40000WHERE Dept = CSE
**This is not possible
7/28/2019 Lecture 5hjjkujku
10/36
Views (contd.) Views containing a join can be ambiguous
UPDATE V1
SET A = a
WHERE C = e
A B
b 1
B C
1 d
1 e
A B C
b 1 d
b 1 e
A B V1 = A B
7/28/2019 Lecture 5hjjkujku
11/36
Views (contd.) Thus, in many DBMSs, views are
updateable only if they are defined on a
single base table.
Views are utilized for
Security mechanism
Convenience
7/28/2019 Lecture 5hjjkujku
12/36
Transaction Basics Concepts
Atomicity Consistency Isolation Durability
T-SQL Commands BEGIN TRANSACTION Begin transaction COMMIT TRANSACTION End transaction ROLLBACK TRANSACTION Cancel transaction
7/28/2019 Lecture 5hjjkujku
13/36
Transaction Basics (contd.) Transferring Rs. 1000 from Account 1234 to Account 2345
Begin Transaction
update Accountset balance = balance - 1000where account_no = 1234
update Account
set balance = balance + 1000where account_no = 2345
Commit transaction
7/28/2019 Lecture 5hjjkujku
14/36
Programming in T-SQL Similar to a programming language,
certain extensions have been made in
SQL to program simple server-sidelogic.
Some of the statements include:Variables
Selection conditions IF () ELSE
Looping
WHILE ()
7/28/2019 Lecture 5hjjkujku
15/36
T-SQL: Variables A Transact-SQL local variable is an object that can
hold a single data value of a specific type.
Variables in batches and scripts are typically used:
As a counter either to count the number of timesa loop is performed or to control how many timesthe loop is performed
To hold a data value to be tested by a control-of-flow statement
To save a data value to be returned by a storedprocedure return code.
7/28/2019 Lecture 5hjjkujku
16/36
T-SQL: Variables (contd.)
The DECLARE statement initializes aTransact-SQL variable by:
Assigning a name. The name must have a single@ as the first character.
Assigning a system-supplied or user-defined datatype and a length. For numeric variables, a
precision and scale are also assigned. Setting the value to NULL.
For example
DECLARE @DeptName VARCHAR(20)
7/28/2019 Lecture 5hjjkujku
17/36
7/28/2019 Lecture 5hjjkujku
18/36
T-SQL: Variables (contd.)
Now we can use the variable in ourscript
For example...
SELECT building
FROM Dept
WHERE deptname = @DeptName
7/28/2019 Lecture 5hjjkujku
19/36
T-SQL: Variables (contd.)
A variable can also have a valueassigned by being referenced in a select
list.
DECLARE @EmpIDVariable INT
SELECT @EmpIDVariable =
MAX(EmployeeID)
FROM Employees
7/28/2019 Lecture 5hjjkujku
20/36
T-SQL: IF statement
Imposes conditions on the execution of aTransact-SQL statement.
IF (SELECT AVG(price) FROM titles) < 15BEGIN
PRINT Inside the IF statement
PRINT Multiple statements have to be encoded in BEGIN END
END
ELSE
PRINT 'Average title price is more than 15.'
7/28/2019 Lecture 5hjjkujku
21/36
T-SQL: WHILE statement
Sets a condition for the repeated execution ofan SQL statement or statement block.
The statements are executed repeatedly aslong as the specified condition is true.
The execution of statements in the WHILEloop can be controlled from inside the loopwith the BREAK and CONTINUE keywords.
7/28/2019 Lecture 5hjjkujku
22/36
T-SQL: WHILE statement(contd.)
BREAK
Causes an exit from the innermost
WHILE loop. Any statements appearingafter the END keyword, marking theend of the loop, are executed.
CONTINUE
Causes the WHILE loop to restart,ignoring any statements after theCONTINUE keyword.
7/28/2019 Lecture 5hjjkujku
23/36
T-SQL: WHILE statement(contd.)
Example
WHILE (SELECT AVG(price) FROM titles) < $30
BEGIN
UPDATE titles
SET price = price * 2 SELECT MAX(price) FROM titles
IF (SELECT MAX(price) FROM titles) > $50BREAK
ELSE
CONTINUE
END
PRINT 'Too much for the market to bear'
7/28/2019 Lecture 5hjjkujku
24/36
Stored Procedures/Functions
Business logic is maintained in database tierfor data intensive operations
E.g. Calculating all interest earned in bankaccounts
In SQL Server 2005, Stored Procedure/
Functions can be written in T-SQL (we will study only this)
Any .NET Language
7/28/2019 Lecture 5hjjkujku
25/36
Stored Procedures/Functions(contd.)
Example
create table emp(
id varchar(200) primary key,
hrs_worked int,
rate float);
7/28/2019 Lecture 5hjjkujku
26/36
Stored Procedures/Functions(contd.)
Function Example
CREATE FUNCTION func_calc_salary (@id varchar) RETURNS floatas
begindeclare @hrs_worked_ intdeclare @rate_ floatdeclare @amt_ float
select @rate_ = e.rate, @hrs_worked_ = e.hrs_worked
from emp ewhere e.id = id
set @amt_ = @rate_* @hrs_worked_return @amt_
end;
7/28/2019 Lecture 5hjjkujku
27/36
Stored Procedures/Functions(contd.)
Calling the function created previously
declare @temp float
exec @temp = calc_salary'e1'
print @temp
7/28/2019 Lecture 5hjjkujku
28/36
Stored Procedures/Functions(contd.)
Procedure Example (with output parameter)
CREATE PROCEDURE proc_calc_salary (@id varchar, @salary float output)as
begindeclare @hrs_worked_ intdeclare @rate_ realdeclare @amt_ float
select @rate_ = e.rate, @hrs_worked_ = e.hrs_worked
from emp ewhere e.id = id
set @amt_ = @rate_* @hrs_worked_set @salary = @amt_
end;
7/28/2019 Lecture 5hjjkujku
29/36
Stored Procedures/Functions(contd.)
Calling a procedure
declare @temp float
exec proc_calc_salary'e1', @temp OUTPUT
print @temp
7/28/2019 Lecture 5hjjkujku
30/36
Triggers
Triggers are useful in enforcingbusiness rules and data integrity.
More powerful than general constraints.
For example,
The employees salary is always less thanhis/her managers salary
7/28/2019 Lecture 5hjjkujku
31/36
7/28/2019 Lecture 5hjjkujku
32/36
T-SQL: Triggers (contd.)
We will learn DML triggers
CREATE TRIGGERtrigger_nameON { table| view}{
{ { FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [, ] [ UPDATE ] [, ]
[DELETE ] }
ASsql_statement[...n]
}
}
7/28/2019 Lecture 5hjjkujku
33/36
T-SQL: Triggers (contd.)
AFTER Specifies that the trigger is fired only when all operations
specified in the triggering SQL statement have executedsuccessfully.
AFTER is the default, if FOR is the only keyword specified. AFTER triggers cannot be defined on views.INSTEAD OF Specifies that the trigger is executed instead ofthe triggering
SQL statement, thus overriding the actions of the triggeringstatements.
At most, one INSTEAD OF trigger per INSERT, UPDATE, orDELETE statement can be defined on a table or view.
[DELETE] [,] [INSERT] [,] [UPDATE] } Are keywords that specify which data modification statements,
when attempted against this tableor view, activate the trigger.At least one option must be specified.
7/28/2019 Lecture 5hjjkujku
34/36
T-SQL: Triggers (contd.)
deleted and inserted are logical(conceptual) tables. They are
structurally similar to the table on whichthe trigger is defined, that is, the tableon which the user action is attempted,
and hold the old values or new valuesof the rows that may be changed by theuser action.
7/28/2019 Lecture 5hjjkujku
35/36
T-SQL: Triggers (contd.)
Example
CREATE TRIGGER check_salON EmployeeFOR INSERT, UPDATEASBEGIN
DECLARE @emp_sal FLOAT,@mgr_sal FLOAT
SELECT @emp_sal = salary
FROM Inserted
SELECT @mgr_sal = E.salaryFROM Inserted I, Dept D, Employee EWHERE I.dno = D.dno AND D.mgr = E.nic
IF @emp_sal > @mgr_sal
ROLLBACK TRANSACTIONEND
7/28/2019 Lecture 5hjjkujku
36/36
Summary
Views
Transaction Basics
T-SQL extensions
Stored Procedures
Triggers