Sunteți pe pagina 1din 77

UNIT -5 Sql-2

Outline:
• Insert, delete, and Update statements in SQL
• Specifying constraints as Assertion and Trigger
• Views(virtual table ) in SQL
• Additional features of SQL
• Database programming issues and techniques
• Embedded SQL
• Dynamic SQL
• Database stored procedures
The Insert Command
Method 1

Method 2 Insert into Employee(Fname, Lname,Dno,Ssn)


values(‘Richard’, ’Mari’, 4, 1234567)

Method 3 Insert into Employee(Fname, Lname,Dno)


values(‘Rich’, ’Ma’, 4)
The Insert Command
Method 4
The Delete Command
• Removes tuples from a relation
• Includes a WHERE clause to select the tuples to
be deleted
Update Command
 Modify attribute values of one or more selected
tuples
 Additional SET clause in the UPDATE command
 Specifies attributes to be modified and new values
Update Command
UPDATE EMPLOYEE set salary=salary*1.1 where Dno
in (Select Dnumber from department where
Dname=‘Research’)
Comparisons Involving NULL
and Three-Valued Logic
• Meanings of NULL
– Unknown value
– Unavailable or withheld value
– Not applicable attribute
• Each individual NULL value considered to be
different from every other NULL value
• SQL uses a three-valued logic:
– TRUE, FALSE, and UNKNOWN (like Maybe)
• NULL = NULL comparison is avoided

Slide 7- 5
Comparisons Involving NULL
and Three-Valued Logic (cont’d.)

Slide 7- 6
Comparisons Involving NULL
and Three-Valued Logic (cont’d.)
• SQL allows queries that check whether an
attribute value is NULL
– IS or IS NOT NULL

Slide 7- 7
Use of WITH
• The WITH clause allows a user to define a
table that will only be used in a particular
query (not available in all SQL
implementations)
• Used for convenience to create a temporary
“View” and use that immediately in a query
• Allows a more straightforward way of looking
a step-by-step query

Slide 7- 12
Example of WITH
• See an alternate approach to doing Q28:
• Q28’: WITH BIGDEPTS (Dno) AS
( SELECT Dno
FROM EMPLOYEE
GROUP BY Dno
HAVING COUNT (*) > 5)
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000 AND Dno IN BIGDEPTS
GROUP BY Dno;

Slide 7- 13
Use of CASE
• SQL also has a CASE construct
• Used when a value can be different based on
certain conditions.
• Can be used in any part of an SQL query
where a value is expected
• Applicable when querying, inserting or
updating tuples

Slide 7- 14
EXAMPLE of use of CASE
• The following example shows that employees are
receiving different raises in different departments
(A variation of the update U6)

• U6’: UPDATE EMPLOYEE


SET Salary =
CASE WHEN Dno = 5 THEN Salary + 2000
WHEN Dno = 4 THEN Salary + 1500
WHEN Dno = 1 THEN Salary + 3000

Slide 7- 15
Constraints as Assertion
• General constraints: constraints that do not
fit in the basic SQL categories

• Mechanism: CREATE ASSERTION


• Components include: a constraint name,
• followed by CHECK, followed by a condition
Assertions: An Example
• “The salary of an employee must not be
greater than the salary of the manager of the
department that the employee works for’’constraint
name,
CREAT ASSERTION SALARY_CONSTRAINT CHECK,
CHECK (NOT EXISTS (SELECT * condition
FROM EMPLOYEE E, EMPLOYEE M,
DEPARTMENT D
WHERE E.SALARY > M.SALARY AND
E.DNO=D.NUMBER AND
D.MGRSSN=M.SSN))

Slide 9- 17
Using general Assertion
• Specify a query that violates the condition.

• Include inside a NOT EXISTS clause

• Query result must be empty

• If the query result is not empty, the assertion has


been violated
SQL triggers
• It is used to monitor a database and initiate
action when a condition occurs
• Triggers are expressed in a syntax similar to
assertions and include the following:
• Event Such as an insert, delete, or update
operation
• Condition
• Action to be taken when the condition is
satisfied
• Triggers are stored programs, which are automatically
executed or fired when some events occur. Triggers are,
in fact, written to be executed in response to any of the
following events −
• A database manipulation (DML) statement (DELETE, INSERT,
or UPDATE)
• A database definition (DDL) statement (CREATE, ALTER, or
DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).
Benefits of Triggers
• Triggers can be written for the following purposes −
• Generating some derived column values automatically
• Enforcing referential integrity
• Event logging and storing information on table access
• Auditing
• Imposing security authorizations
• Preventing invalid transactions
The syntax for creating a trigger is
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name] ON table_name
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the
trigger will be executed. The INSTEAD OF clause is used for
creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the
DML operation.
• [OF col_name] − This specifies the column name that will be
updated.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the
trigger will be executed for each row being affected.
This trigger will display the salary difference between
the old values and new values −
• CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
• INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

The UPDATE statement will update an existing record in the table −

UPDATE customers
SET salary = salary + 500
WHERE id = 2;

Output: Old salary: 1500


New salary: 2000
Salary difference: 500
Trigger for when New Sal is less then the old salary

SQL> Create or Replace trigger Salary_update_check


Before Update of Salary on tbl_employess
For Each Row
Begin
If :New.Salary < :old.Salary then
Raise_Application_error(-20125,’Updated Salary cannot be lesser then
current Salary’);
End if;
END;
SQL> Update tbl_employees
Set Salary=5000 where empid=106;
• SQL> Create OR Replace Trigger emp_insert
After insert on tbl_employees
Begin
DBMS_output.put_line(‘Record inserted’);
End;
SQL> insert into tbl_employees values(105,’john’,’cena’,6000,30);
Record inserted.
1 row created. (Message will be displayed.
Restricted insertion
• Create or Replace Trigger restricted_insert
Before insert on tbl_employees
begin
If(To_char(Sysdate,’HH24:MI’) Not Between
‘09:00’ AND ‘18:00’) then
Raise_Application_Error(-20123,’You can add employee
only between 9:00 AM and 6:00 PM’)
End IF;
END;
SQL trigger example

A trigger to compare an employee’s salary to


his/her supervisor during insert or update
operations

CREATE TRIGGER INFORM_SUPERVISOR


BEFORE INSERT OR UPDATE OF Event
SALARY, SUPERVISOR_SSN ON EMPLOYEE
FOR EACH ROW
WHEN
(NEW.SALARY> (SELECT SALARY FROM EMPLOYEE
WHERE SSN=NEW.SUPERVISOR_SSN)) Condition
INFORM_SUPERVISOR (NEW.SUPERVISOR_SSN,NEW.SSN);
Action
If acc balance <=0,acc will be
automatically blocked
Create trigger overdraft
after update on pre-paid
Referencing new row as nrow
for each row
When nrow. balance <= 0
update pre-paid
set blocked = ‘T’;

For every pre-paid account whose balance is less than or


equal to 0, the account is automatically marked as
“blocked”.
View In Sql
 A view is a “virtual” table that is derived from
other tables
 Does not necessarily exist in physical form
 Allows for limited update/modify operations
 Allows full query operations
 A convenience for expressing certain operations
Specification of Views
• SQL command: CREATE VIEW
• a table (view) name
• a possible list of attribute names (for example,
when arithmetic operations are specified or
when we want the names to be different from
the attributes in the base relations)
• a query to specify the table contents
SQL view: An example
CREATE VIEW WORKS_ON1 AS
SELECT FNAME, LNAME, PNAME, HOURS
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE SSN=ESSN AND PNO=PNUMBER

WORKS_ON1
Fname Lname Pname Hours
View example

DEPT_INFO
Dept_name No_Of_emp Total_sal
Query using View
Q. Retrieve first name and last name of
employee who work for productX project

SELECT FNAME, LNAME FROM WORKS_ON1


WHERE PNAME=‘ProductX’;

WORKS_ON1
Fname Lname Pname Hours
Dropping a View
A view should be always up to date

If we modify base table on which view is defined, the


view must also be modified.

DROP VIEW WORKS_ON1

WORKS_ON1

Fname Lname Pname Hours


Update View
 Update on a view defined on a single table
without any aggregate functions
 Update may map to an update on the
underlying base table

Views involving joins: An update may map to an


update on the underlying base relations in
multiple ways but not always possible
Update View(Some Rules)
 A view with single defining table is updatable if the
view attributes contain the primary key of base
relation
 View defined on multiple table using join are generally
not updatable.
 Views defined using aggregation function and
grouping are not updatable.
Example
UPDATE WORKS_ON1
SET PNAME = 'ProductY‘
WHERE LNAME = 'SMITH' AND FNAME = 'JOHN’ AND
PNAME = 'ProductX'
----------
• solution:
----------
• SET PNAME = 'ProductY'
• *
• ERROR at line 2:
• ORA-01779: cannot modify a column which maps to a non
key-preserved table
EXPANDED Block Structure of SQL
Queries

Slide 7- 40
Database Programming
Objective:
• To access a database from an application
program (as opposed to interactive interfaces)
• A majority of database operations are made
through application programs (increasingly
through web application)
Database Programming Approaches
• 1. Embedded SQL: database commands are embedded in a general-
purpose programming language
exec sql, end exec
• Precompiler scans the source program and identify database
statements and extracts

• 2. Library of database functions: available to the host language for


database calls; known as an API

• SQLCONNECT, SQLBINDParameter, SQLEXECUTE …

• 3. A brand new, full-fledged language (minimizes impedance


mismatch)
PL/SQL
Steps in database programming
1. Client program opens a connection to the
database server

2. Client program submits queries to and/or updates


the database

3. When database access is no longer needed, client


program closes (terminates) the connection
SQL Commands for
Connecting to a Database
• Connection (multiple connections are possible but only
one is active)
CONNECT TO server-name AS connection-name
AUTHORIZATION user-account-info;
• Change from an active connection to another one
SET CONNECTION connection-name;
• Disconnection
DISCONNECT connection-name;

For e.g.
CONNECT TO Raj.gat.com AS sysdba AUTHORIZATION
raj/pwd;
Embedded SQL
• SQL is not enough! Needs to be embedded in a general
purpose language to get
– GUI
– Flow of control
– Generate SQL dynamically based on user input
• SQL commands can be called from within a host language
(e.g., C/C++, Basic, .NET or Java) program or scripting
language (e.g., PHP, Ruby).
• A query answer is a bag of records - with arbitrarily many
rows! No such data structure in most languages. Called
impedance mismatch.
• The SQL standard supports a cursor to handle this
Embedded SQL
• Most SQL statements can be embedded in a
general-purpose host programming language
such as COBOL, C, Java
• An embedded SQL statement is distinguished
from the host language statements by EXEC
SQL or EXEC SQL BEGIN and a matching END EXEC
or EXEC SQL END (or semicolon)

– shared variables (used in both languages) usually


prefixed with a colon (:) in SQL
Example: Variable declaration
 Variables inside DECLARE are shared and can appear (while
prefixed by a colon) in SQL statements

 SQLCODE is used to communicate errors/exceptions between


the database and the program

int loop;
EXEC SQL BEGIN DECLARE SECTION;
varchar dname[16], fname[16], …;
char ssn[10], bdate[11], …;
int dno, dnumber;
int SQLCODE;
char SQLSTATE[6];
EXEC SQL END DECLARE SECTION;
SQL code and state
 SQLCODE and SQLSTATE are communication
variables
 Used by DBMS to communicate exceptions or error
conditions to the program
 SQLCODE: integer variable
After each DBMS command is executed, DBMS
returns a value in SQLCODE
SQLCODE > 0; no more records are available
= 0; statement executed successfully
< 0; some error has occurred
Cont..

SQLSTATE: string of five characters

SQLSTATE = 00000; no error or exception

SQLSTATE= other values; various error and


exception

SQLSTATE=02000 ; no data
Program segment using embedded
SQL
loop = 1;
while (loop) {
prompt (“Enter SSN: “, ssn);
EXEC SQL
select FNAME, LNAME, ADDRESS, SALARY
into :fname, :lname, :address, :salary
from EMPLOYEE where SSN == :ssn;
if (SQLCODE == 0)
printf(fname,minit,lname);
else printf(“SSN does not exist: “, ssn);
prompt(“More SSN? (1=yes, 0=no): “, loop)
END-EXEC
}
Program segment using embedded
SQL
EXEC SQL select S.sname, S.age
into :c_sname, :c_age
from Sailors S
where S.sid=:c_sid;
END EXEC
EXEC SQL select S.sname, S.age
from Sailors S
where S.rating>:c_minrating;
END EXEC
Embedded SQL in C-Retrieving multiple Tuples
example
• A cursor (iterator) is needed to process multiple
tuples.
– Points to a single tuple at a time from result of query
• FETCH commands move the cursor to the next
tuple
• OPEN CURSOR starts the sql execution
– It fetches query result and set cursor to a position before first row
in result .
– It becomes current row for cursor.
• CLOSE CURSOR indicates that the processing of
query results has been completed
General Form of a Cursor

DECLARE <Cursor name>[INSENSITIVE][SCROLL]CURSOR


[WITH HOLD]
FOR <query specification>
[ORDER BY<ordering specification>]
[For READ ONLY|FOR UPDATE]

DECLARE Emp CURSOR FOR <Query>


Declare sinfo CURSOR FOR
select S.sname, S.age
from Sailors S
where S.rating>:c_minrating;

Open sinfo;
Fetch sinfo INTO :c_name, :c_age;
CLOSE sinfo;
UPDATE Sailor S
SET S.rating=S.rating-1
WHERE CURRENT of sinfo;

DELETE FROM Sailor S


Where CURRENT of sinfo;
Dynamic SQL
• Objective: executing new (not previously compiled)
SQL statements at run-time
– a program accepts SQL statements from the keyboard at
run-time
• Dynamic update is relatively simple; dynamic query
can be complex
– because the type and number of retrieved attributes are
unknown at compile time
Dynamic SQL: An Example
Example
EXEC SQL BEGIN DECLARE SECTION;
char sqlcommand[]={“DELETE FROM Sailors
WHERE rating>5”}
EXEC SQL END DECLARE SECTION;
EXEC SQL PREPARE sqlcommand FROM :sqlupdatestring;
EXEC SQL EXECUTE sqlcommand;
Database stored procedure
 Persistent procedures/functions (modules) are
stored locally and executed by the database server.
 As opposed to execution by clients

Advantages:
i) If the procedure is needed by many applications, it
can be invoked by any of them (thus reduce
duplications).
ii) Execution by the server reduces communication
costs
iii) Enhance the modeling power of views
Database stored procedure

Disadvantages:

Every DBMS has its own syntax and this can make the
system less portable
stored procedure construct
A stored procedure
CREATE PROCEDURE <procedure-name >(parameters)
<local-declarations>
<procedure-body>;
A stored function
CREATE FUNCTION <fun-name>(parameters)
RETRUNS return-type
local-declarations
function-body;
Calling a procedure or function
CALL procedure-name/fun-name (arguments);
stored procedure construct
A stored procedure written in general purpose
language

CREATE PROCEDURE <procedure-name >(parameters)


LANGUAGE<Programming language name>
EXTERNAL NAME<file path name>

Parameter Type: SQL data type


Parameter Mode: IN,OUT,INOUT
EXEC SQL BEGIN DECLARE SECTION;
Char isbn[10];
Long qty;
EXEC SQL END DECLARE SECTION;
………………
EXEC SQL CALL procedure-name/fun-name
(arguments);
SQL Persistent Stored Modules (PSM)
SQL/PSM:
Part of the SQL standard for writing persistent stored
modules

SQL + stored procedures/functions + additional


programming constructs

E.g., branching and looping statements

Enhance the power of SQL


SQL/PSM: Extending SQL for Specifying
Persistent Stored Modules
Conditional branching statement:

IF <condition> THEN <statement list>


ELSEIF <condition> THEN <statement list>
...
ELSEIF <condition> THEN <statement list>
ELSE <statement list>
END IF
Looping constructs

FOR <loop name> as <cursor name> CURSOR


FOR<query> Do <statement list>
END FOR
SQL/PSM Example
CREATE FUNCTION DEPT_SIZE (IN deptno INTEGER)
RETURNS VARCHAR[7]
DECLARE TOT_EMPS INTEGER;

SELECT COUNT (*) INTO :TOT_EMPS


FROM SELECT EMPLOYEE WHERE DNO = :deptno;

IF TOT_EMPS > 100 THEN RETURN “HUGE”

ELSEIF TOT_EMPS > 50 THEN RETURN “LARGE”

ELSEIF TOT_EMPS > 30 THEN RETURN “MEDIUM”


ELSE RETURN “SMALL”
ENDIF;
Problem Statement
Write a Function Rate which will rate a class
based on the total no of students.

<100 students: Unpopular


<200 students: Average
>=200 students: Very popular
Solution
CREATE FUNCTION Rate (IN b CHAR(20) )
Number of
RETURNS CHAR(10) customers of
DECLARE cust INTEGER; bar b

(SELECT COUNT(*) into cust FROM Frequents


WHERE bar = b);
IF cust < 100 THEN RETURN ’unpopular’
ELSEIF cust < 200 THEN RETURN ’average’
ELSE RETURN ’popular’
END IF; Nested
IF statement
CREATE PROCEDURE getemployee
IS
BEGIN
select fname,sex
from employee
END;

EXEC getemployee;
CREATE OR REPLACE PROCEDURE
p_update_salary(p_dept_id IN number,
p_sal_incr IN number)
IS
BEGIN
update employee
set salary=salary+(salary*p_sal_incr)
where dept_id=p_dept_id;
DBMS_output.putline(‘salary updated for
p_dept_id’)
END;

EXEC p_update_salary(10,0.10);
CREATE OR REPLACE PROCEDURE p_update_salary
IS
BEGIN
update employee
Set salary=salary+(salary*0.10)
Where dept_id=10;
DBMS_output.putline(‘salary updated’)
END;

EXEC p_update_salary;
CREATE OR REPLACE PROCEDURE p_update_salary (p_dept_id IN
number, p_sal_incr IN number, p_first_name OUT varchar)
IS
BEGIN
select fname into p_first_name
from employee
where dept_id=p_dept_id;

Update employee
set salary=salary+(salary*p_sal_incr)
where dept_id=p_dept_id;

DBMS_output.putline(‘salary updated’)
END;

EXEC p_update_salary;