You are on page 1of 36

Database Management Systems II

Lecture 5

Last Lecture

Relational Algebra SQL (DDL, DML, SELECT) Any questions?

This lecture

Views SQL extensions (specifically T-SQL)

Transaction Basics
Triggers Stored Procedures

Views

A view is a virtual table A view is based on base tables or defining tables In SQL, CREATE VIEW statement is used to define views

Views (contd.)
Example Create a view of student names & their majoring department

CREATE VIEW STUD_MAJ AS SELECT S.Name, D.Name FROM STUDENT S INNER JOIN DEPARTMENT D ON (S.Major = D.DeptID)

Views (contd.)
Another example View of departments and their average salary CREATE VIEW DEPT_SAL (Dept, AvgSalary) AS SELECT D.Name, AVG(E.Salary) FROM EMPLOYEE E INNER JOIN DEPARTMENT D ON (E.Dept = D.DeptID) GROUP BY D.Name

Views (contd.)

Now, we can query the view similar to a table

Example.. List the 30,000 SELECT FROM WHERE

departments with average salary > Dept DEPT_SAL AvgSalary > 30,000

Views (contd.)

Dropping a view...

DROP VIEW DEPT_SAL

Views (contd.)

Updating a view can be ambiguous

Views containing aggregate functions are not updateable

Example
UPDATE DEPT_SAL SET AvgSalary = 40000 WHERE Dept = CSE **This is not possible

Views (contd.)

Views containing a join can be ambiguous


B 1 B 1 C d A b b B 1 1 C d e

A b

V1 = A

UPDATE V1 SET A = a WHERE C = e

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

Transaction Basics

Concepts

Atomicity Consistency Isolation Durability

T-SQL Commands

BEGIN TRANSACTION Begin transaction COMMIT TRANSACTION End transaction ROLLBACK TRANSACTION Cancel transaction

Transaction Basics (contd.)

Transferring Rs. 1000 from Account 1234 to Account 2345

Begin Transaction update Account set balance = balance - 1000 where account_no = 1234 update Account set balance = balance + 1000 where account_no = 2345 Commit transaction

Programming in T-SQL

Similar to a programming language, certain extensions have been made in SQL to program simple server-side logic. Some of the statements include:

Variables Selection conditions

IF () ELSE
WHILE ()

Looping

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 times a loop is performed or to control how many times the loop is performed To hold a data value to be tested by a control-offlow statement To save a data value to be returned by a stored procedure return code.

T-SQL: Variables (contd.)

The DECLARE statement initializes a Transact-SQL variable by:

Assigning a name. The name must have a single @ as the first character. Assigning a system-supplied or user-defined data type and a length. For numeric variables, a precision and scale are also assigned. Setting the value to NULL.

For example

DECLARE @DeptName VARCHAR(20)

T-SQL: Variables (contd.)

When a variable is first declared, its value is set to NULL.

To assign a value to a variable, use the SET statement. For example,

SET @DeptName = Sales

T-SQL: Variables (contd.)

Now we can use the variable in our script

For example...

SELECT building FROM Dept WHERE deptname = @DeptName

T-SQL: Variables (contd.)

A variable can also have a value assigned by being referenced in a select list. DECLARE @EmpIDVariable INT SELECT @EmpIDVariable = MAX(EmployeeID) FROM Employees

T-SQL: IF statement

Imposes conditions on the execution of a Transact-SQL statement. IF (SELECT AVG(price) FROM titles) < 15 BEGIN
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.'

T-SQL: WHILE statement

Sets a condition for the repeated execution of an SQL statement or statement block. The statements are executed repeatedly as long as the specified condition is true. The execution of statements in the WHILE loop can be controlled from inside the loop with the BREAK and CONTINUE keywords.

T-SQL: WHILE statement (contd.)

BREAK Causes an exit from the innermost WHILE loop. Any statements appearing after the END keyword, marking the end of the loop, are executed. CONTINUE Causes the WHILE loop to restart, ignoring any statements after the CONTINUE keyword.

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) > $50 BREAK ELSE CONTINUE END PRINT 'Too much for the market to bear'

Stored Procedures/Functions

Business logic is maintained in database tier for data intensive operations

E.g. Calculating all interest earned in bank accounts

In SQL Server 2005, Stored Procedure/ Functions can be written in


T-SQL (we will study only this) Any .NET Language

Stored Procedures/Functions (contd.)

Example

create table emp( id varchar(200) primary key, hrs_worked int, rate float);

Stored Procedures/Functions (contd.)

Function Example

CREATE FUNCTION func_calc_salary (@id varchar) RETURNS float as begin declare @hrs_worked_ int declare @rate_ float declare @amt_ float select @rate_ = e.rate, @hrs_worked_ = e.hrs_worked from emp e where e.id = id set @amt_ = @rate_* @hrs_worked_ return @amt_ end;

Stored Procedures/Functions (contd.)

Calling the function created previously

declare @temp float exec @temp = calc_salary'e1' print @temp

Stored Procedures/Functions (contd.)

Procedure Example (with output parameter)

CREATE PROCEDURE proc_calc_salary (@id varchar, @salary float output) as begin declare @hrs_worked_ int declare @rate_ real declare @amt_ float select @rate_ = e.rate, @hrs_worked_ = e.hrs_worked from emp e where e.id = id set @amt_ = @rate_* @hrs_worked_ set @salary = @amt_ end;

Stored Procedures/Functions (contd.)

Calling a procedure

declare @temp float exec proc_calc_salary'e1', @temp OUTPUT print @temp

Triggers

Triggers are useful in enforcing business rules and data integrity.

More powerful than general constraints.


For example,

The employees salary is always less than his/her managers salary

T-SQL: Triggers

A trigger is a special type of stored procedure that automatically takes effect when the data in a specified table is modified. A trigger is invoked in response to a

DDL statement (CREATE, ALTER etc.) or DML statement (INSERT, UPDATE, or DELETE statement).

T-SQL: Triggers (contd.)

We will learn DML triggers


CREATE TRIGGER trigger_name ON { table | view } { { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [DELETE ] } AS sql_statement [ ...n ] } }

T-SQL: Triggers (contd.)


AFTER Specifies that the trigger is fired only when all operations specified in the triggering SQL statement have executed successfully. 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 of the triggering SQL statement, thus overriding the actions of the triggering statements. At most, one INSTEAD OF trigger per INSERT, UPDATE, or DELETE statement can be defined on a table or view. [DELETE] [,] [INSERT] [,] [UPDATE] } Are keywords that specify which data modification statements, when attempted against this table or view, activate the trigger. At least one option must be specified.

T-SQL: Triggers (contd.)

deleted and inserted are logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is attempted, and hold the old values or new values of the rows that may be changed by the user action.

T-SQL: Triggers (contd.)

Example CREATE TRIGGER check_sal ON Employee FOR INSERT, UPDATE AS BEGIN DECLARE @emp_sal FLOAT, @mgr_sal FLOAT SELECT @emp_sal = salary FROM Inserted

SELECT @mgr_sal = E.salary FROM Inserted I, Dept D, Employee E WHERE I.dno = D.dno AND D.mgr = E.nic
IF @emp_sal > @mgr_sal ROLLBACK TRANSACTION

END

Summary

Views Transaction Basics T-SQL extensions Stored Procedures Triggers

You might also like