SlideShare a Scribd company logo
Chapter Outline
9.1 General Constraints as Assertions
9.2 Views in SQL
9.3 Database Programming
9.4 Embedded SQL
9.5 Functions Calls, SQL/CLI
9.6 Stored Procedures, SQL/PSM
9.7 Summary
Chapter Objectives
• Specification of more general constraints via
assertions
• SQL facilities for defining views (virtual tables)
• Various techniques for accessing and
manipulating a database via programs in
general-purpose languages (e.g., Java)
Constraints as Assertions
• General constraints: constraints that do not
fit in the basic SQL categories (presented in
chapter 8)
• Mechanism: CREAT 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’’
CREAT ASSERTION SALARY_CONSTRAINT
CHECK (NOT EXISTS (SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D
WHERE E.SALARY > M.SALARY AND
E.DNO=D.NUMBER AND D.MGRSSN=M.SSN))
Using General Assertions
• 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
• Objective: to monitor a database and take
action when a condition occurs
• Triggers are expressed in a syntax similar to
assertions and include the following:
– event (e.g., an update operation)
– condition
– action (to be taken when the condition is satisfied)
SQL Triggers: An 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
SALARY, SUPERVISOR_SSN ON EMPLOYEE
FOR EACH ROW
WHEN
(NEW.SALARY> (SELECT SALARY FROM EMPLOYEE
WHERE SSN=NEW.SUPERVISOR_SSN))
INFORM_SUPERVISOR (NEW.SUPERVISOR_SSN,NEW.SSN;
Views in SQL
• A view is a “virtual” table that is derived from
other tables
• Allows for limited update operations (since
the table may not physically be stored)
• Allows full query operations
• A convenience for expressing certain
operations
What is a View?
• In SQL, a VIEW is a virtual relation based on the result-set
of a SELECT statement.
• A view contains rows and columns, just like a real table.
The fields in a view are fields from one or more real tables
in the database. In some cases, we can modify a view and
present the data as if the data were coming from a single
table.
• Syntax:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
SQL – Relations, Tables & Views
• When we say Relation, it could be a Table or a View. There
are three kind of relations:
1. Stored relations tables
We sometimes use the term “base relation” or “base table”
2. Virtual relations views
3. Temporary results
SQL – Create View
• Example: Create a view with title and year and made by
Paramount studio.
Movie (title, year, length, inColor, studioName,
producerC#)
CREATE VIEW ParamountMovie AS
SELECT title,year
FROM Movie
WHERE studioName = ‘Paramount’;
SQL – Querying View
• A view could be used from inside a query, a stored
procedure, or from inside another view. By adding functions,
joins, etc., to a view, it allows us to present exactly the data
we want to the user.
SELECT title
FROM ParamountMovie
WHERE year = ‘1979’;
• Have same result as
SELECT title
FROM Movie
WHERE studioName = ‘Paramount’ AND year = ‘1979’;
View
Table
SQL - Querying View con’t
• Query involving both view and table
SELECT DISTINCT starName
FROM ParamountMovie, StarsIn
WHERE title = movieTitle AND year = movieYear;
Table
View
SQL - Querying View example
Movie (title, year, length, inColor, studioName, producerC#)
MovieExec (name, address, cert#, netWorth)
CREATE VIEW MovieProd AS
SELECT title, name
FROM Movie, MovieExec
WHERE producerC# = cert#;
SELECT name
FROM MovieProd
WHERE title = ‘Gone With the Wind’;
• Same result as query from tables
SELECT name
FROM Movie, MovieExec
WHERE producerC# = cert# AND title = ‘The War Of the World’;
SQL - Renaming Attributes in View
• Sometime, we might want to distinguish
attributes by giving the different name.
CREATE VIEW MovieProd (movieTitle, prodName) AS
SELECT title, name
FROM Movie, MovieExec
WHERE producerC# = cert#;
SQL - Modifying View
When we modify a view, we actually modify a table through
a view. Many views are not updateable. Here are rules
have been defined in SQL for updateable views:
• selecting (SELECT not SELECT DISTINCT) some attributes
from one relation R (which may itself be an updateable
view)
 The WHERE clause must not involve R in a subquery.
 The list in the SELECT clause must include enough
attributes that will allow us to insert tuples into the
view as well as table. All other attributes will be filled
out with NULL or the proper default values.
SQL – Modifying View (INSERT)
INSERT INTO ParamountMovie
VALUES (‘Star Trek’, 1979);
To make the view ParamountMovie updateable, we need to add
attribute studioName to it’s SELECT clause because it makes more
sense if the studioName is Paramount instead of NULL.
CREATE VIEW ParamountMovie AS
SELECT studioName, title, year
FROM Movie
WHERE studioName = ‘Paramount’;
Then
INSERT INTO ParamountMovie
VALUES (‘Paramount’, ‘Star Trek’, 1979);
Title year length inColor studioName producerC#
‘Star Trek’ 1979 0 NULL ‘Paramount’ NULL
SQL - Modifying View (DELETE)
• Suppose we wish to delete all movies with “Trek” in
their title from the updateable view
ParamountMovie.
DELETE FROM ParamountMovie
WHERE title LIKE ‘%Trek%’;
It is turned into the base table delete
DELETE FROM Movie
WHERE title LIKE ‘%Trek%’ AND studioName = ‘Paramount’;
SQL - Modifying View (UPDATE)
• UPDATE from an updateable view
UPDATE ParamountMovie
SET year = 1979
WHERE title = ‘Star Trek the Movie’;
It is turned into the base table update
UPDATE Movie
SET year = 1979
WHERE title = ‘Star Trek the Movie’ AND studioName =
‘Paramount’;
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 Views: An Example
• Specify a different WORKS_ON table
CREATE TABLE WORKS_ON_NEW AS
SELECT FNAME, LNAME, PNAME, HOURS
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE SSN=ESSN AND PNO=PNUMBER
GROUP BY PNAME;
Using a Virtual Table
• We can specify SQL queries on a newly create
table (view):
SELECT FNAME, LNAME FROM WORKS_ON_NEW
WHERE PNAME=‘Seena’;
• When no longer needed, a view can be
dropped:
DROP WORKS_ON_NEW;
Efficient View Implementation
• Query modification: present the view query in
terms of a query on the underlying base tables
– disadvantage: inefficient for views defined via
complex queries (especially if additional queries
are to be applied to the view within a short time
period)
Efficient View Implementation
• View materialization: involves physically
creating and keeping a temporary table
– assumption: other queries on the view will follow
– concerns: maintaining correspondence between
the base table and the view when the base table is
updated
– strategy: incremental update
View Update
• Update on a single view without aggregate
operations: 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
– not always possible
Un-updatable Views
• Views defined using groups and aggregate
functions are not updateable
• Views defined on multiple tables using joins
are generally not updateable
• WITH CHECK OPTION: must be added to the
definition of a view if the view is to be
updated
– to allow check for updatability and to plan for an
execution strategy
Database Programming
• Objective: to access a database from an
application program (as opposed to
interactive interfaces)
• Why? An interactive interface is convenient
but not sufficient; a majority of database
operations are made thru application
programs (nowadays thru web applications)
Database Programming Approaches
• Embedded commands: database commands
are embedded in a general-purpose
programming language
• Library of database functions: available to the
host language for database calls; known as an
API
• A brand new, full-fledged language
(minimizes impedance mismatch)
Impedance Mismatch
• Incompatibilities between a host
programming language and the database
model, e.g.,
– type mismatch and incompatibilities; requires a
new binding for each language
– set vs. record-at-a-time processing
• need special iterators to loop over query results and
manipulate individual values
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 terminates the connection
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 and a matching END-EXEC (or
semicolon)
– shared variables (used in both languages) usually
prefixed with a colon (:) in SQL
Example: Variable Declaration
in Language C
• 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, SQLCODE, …;
EXEC SQL END DECLARE SECTION;
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;
Embedded SQL in C
Programming Examples
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, …);
else printf(“SSN does not exist: “, ssn);
prompt(“More SSN? (1=yes, 0=no): “, loop);
END-EXEC
}
Embedded SQL in C
Programming Examples
• A cursor (iterator) is needed to process
multiple tuples
• FETCH commands move the cursor to the
next tuple
• CLOSE CURSOR indicates that the
processing of query results has been
completed
Dynamic SQL
• Objective: executing new (not previously compiled)
SQL statements at run-time
– a program accepts SQL statements from the keyboard at
run-time
– a point-and-click operation translates to certain SQL query
• 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
EXEC SQL BEGIN DECLARE SECTION;
varchar sqlupdatestring[256];
EXEC SQL END DECLARE SECTION;
…
prompt (“Enter update command:“, sqlupdatestring);
EXEC SQL PREPARE sqlcommand FROM :sqlupdatestring;
EXEC SQL EXECUTE sqlcommand;
Embedded SQL in Java
• SQLJ: a standard for embedding SQL in Java
• An SQLJ translator converts SQL statements
into Java (to be executed thru the JDBC
interface)
• Certain classes, e.g., java.sql have to be
imported
Java Database Connectivity
• JDBC: SQL connection function calls for Java
programming
• A Java program with JDBC functions can
access any relational DBMS that has a JDBC
driver
• JDBC allows a program to connect to several
databases (known as data sources)
Steps in JDBC Database Access
1. Import JDBC library (java.sql.*)
2. Load JDBC driver:
Class.forname(“oracle.jdbc.driver.OracleDriver”)
3. Define appropriate variables
4. Create a connect object (via getConnection)
5. Create a statement object from the
Statement class:
1. PreparedStatment
2. CallableStatement
Steps in JDBC Database Access
(continued)
6. Identify statement parameters (to be
designated by question marks)
7. Bound parameters to program variables
8. Execute SQL statement (referenced by an
object) via JDBC’s executeQuery
9. Process query results (returned in an object
of type ResultSet)
– ResultSet is a 2-dimentional table
Embedded SQL in Java:
An Example
ssn = readEntry(“Enter a SSN: “);
try {
#sql{select FNAME< LNAME, ADDRESS, SALARY
into :fname, :lname, :address, :salary
from EMPLOYEE where SSN = :ssn};
}
catch (SQLException se) {
System.out.println(“SSN does not exist: “,+ssn);
return;
}
System.out.println(fname+“ “+lname+… );
Multiple Tuples in SQLJ
• SQLJ supports two types of iterators:
– named iterator: associated with a query result
– positional iterator: lists only attribute types in a
query result
• A FETCH operation retrieves the next tuple in a
query result:
fetch iterator-variable into program-variable
Database Programming with Functional Calls
• Embedded SQL provides static database
programming
• API: dynamic database programming with a
library of functions
– advantage: no preprocessor needed (thus more
flexible)
– drawback: SQL syntax checks to be done at run-
time
SQL Call Level Interface
• A part of the SQL standard
• Provides easy access to several databases
within the same program
• Certain libraries (e.g., sqlcli.h for C) have
to be installed and available
• SQL statements are dynamically created and
passed as string parameters in the calls
Components of SQL/CLI
• Environment record: keeps track of database
connections
• Connection record: keep tracks of info needed
for a particular connection
• Statement record: keeps track of info needed
for one SQL statement
• Description record: keeps track of tuples
Steps in C and SQL/CLI Programming
1. Load SQL/CLI libraries
2. Declare record handle variables for the above
components (called: SQLHSTMT, SQLHDBC, SQLHENV,
SQLHDEC)
3. Set up an environment record using SQLAllocHandle
4. Set up a connection record using SQLAllocHandle
5. Set up a statement record using SQLAllocHandle
Steps in C and SQL/CLI Programming (continued)
6. Prepare a statement using SQL/CLI function
SQLPrepare
7. Bound parameters to program variables
8. Execute SQL statement via SQLExecute
9. Bound columns in a query to a C variable via
SQLBindCol
10. Use SQLFetch to retrieve column values into
C variables
Database Stored Procedures
• Persistent procedures/functions (modules) are
stored locally and executed by the database server
(as opposed to execution by clients)
• Advantages:
– if the procedure is needed by many applications, it can be
invoked by any of them (thus reduce duplications)
– execution by the server reduces communication costs
– enhance the modeling power of views
Stored Procedure Constructs
• A stored procedure
CREATE PROCEDURE procedure-name (params)
local-declarations
procedure-body;
• A stored function
CREATE FUNCTION fun-name (params) RETRUNS return-type
local-declarations
function-body;
• Calling a procedure or function
CALL procedure-name/fun-name (arguments);
SQL Persistent Stored Modules
• 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: An 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;
Summary
• Assertions provide a means to specify
additional constraints
• Triggers are a special kind of assertions; they
define actions to be taken when certain
conditions occur
• Views are a convenient means for creating
temporary (virtual) tables
Summary (continued)
• A database may be accessed via an interactive
database
• Most often, however, data in a database is
manipulate via application programs
• Several methods of database programming:
– embedded SQL
– dynamic SQL
– stored procedure and function

More Related Content

Similar to chap 9 dbms.ppt

PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
metsarin
 
Erik_van_Roon.pdf
Erik_van_Roon.pdfErik_van_Roon.pdf
Erik_van_Roon.pdf
DetchDuvanGaelaCamar
 
Udf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayiUdf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayi
Muhammed Thanveer M
 
My sql udf,views
My sql udf,viewsMy sql udf,views
DBAdapters
DBAdaptersDBAdapters
DBAdapters
XAVIERCONSULTANTS
 
Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019
Antonios Chatzipavlis
 
Designing and Creating Views, Inline Functions, and Synonyms
 Designing and Creating Views, Inline Functions, and Synonyms Designing and Creating Views, Inline Functions, and Synonyms
Designing and Creating Views, Inline Functions, and Synonyms
Tayba Farooqui
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
maxpane
 
Plsql guide 2
Plsql guide 2Plsql guide 2
Plsql guide 2
Vinay Kumar
 
Rolta’s application testing services for handling ever changing environment.
Rolta’s application testing services for handling ever changing environment.   Rolta’s application testing services for handling ever changing environment.
Rolta’s application testing services for handling ever changing environment.
Rolta
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
Jürgen Ambrosi
 
6232 b 04
6232 b 046232 b 04
Les10
Les10Les10
Les11.ppt
Les11.pptLes11.ppt
Introduction to mysql part 4
Introduction to mysql part 4Introduction to mysql part 4
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
Sankhya_Analytics
 
PLSQLIntroduction.ppt
PLSQLIntroduction.pptPLSQLIntroduction.ppt
PLSQLIntroduction.ppt
Semra D.
 
Sql views
Sql viewsSql views
Sql views
arshid045
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sql
Nazir Ahmed
 
Admin Guiding Query Plans
Admin Guiding Query PlansAdmin Guiding Query Plans
Admin Guiding Query Plans
rsnarayanan
 

Similar to chap 9 dbms.ppt (20)

PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Erik_van_Roon.pdf
Erik_van_Roon.pdfErik_van_Roon.pdf
Erik_van_Roon.pdf
 
Udf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayiUdf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayi
 
My sql udf,views
My sql udf,viewsMy sql udf,views
My sql udf,views
 
DBAdapters
DBAdaptersDBAdapters
DBAdapters
 
Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019
 
Designing and Creating Views, Inline Functions, and Synonyms
 Designing and Creating Views, Inline Functions, and Synonyms Designing and Creating Views, Inline Functions, and Synonyms
Designing and Creating Views, Inline Functions, and Synonyms
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
Plsql guide 2
Plsql guide 2Plsql guide 2
Plsql guide 2
 
Rolta’s application testing services for handling ever changing environment.
Rolta’s application testing services for handling ever changing environment.   Rolta’s application testing services for handling ever changing environment.
Rolta’s application testing services for handling ever changing environment.
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
 
6232 b 04
6232 b 046232 b 04
6232 b 04
 
Les10
Les10Les10
Les10
 
Les11.ppt
Les11.pptLes11.ppt
Les11.ppt
 
Introduction to mysql part 4
Introduction to mysql part 4Introduction to mysql part 4
Introduction to mysql part 4
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
PLSQLIntroduction.ppt
PLSQLIntroduction.pptPLSQLIntroduction.ppt
PLSQLIntroduction.ppt
 
Sql views
Sql viewsSql views
Sql views
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sql
 
Admin Guiding Query Plans
Admin Guiding Query PlansAdmin Guiding Query Plans
Admin Guiding Query Plans
 

More from arjun431527

classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
Unit - 1.pptx
Unit - 1.pptxUnit - 1.pptx
Unit - 1.pptx
arjun431527
 
chap 10 dbms.pptx
chap 10 dbms.pptxchap 10 dbms.pptx
chap 10 dbms.pptx
arjun431527
 
Aditi's Tech.pdf
Aditi's Tech.pdfAditi's Tech.pdf
Aditi's Tech.pdf
arjun431527
 
ds_mod1.pdf
ds_mod1.pdfds_mod1.pdf
ds_mod1.pdf
arjun431527
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
arjun431527
 

More from arjun431527 (6)

classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
Unit - 1.pptx
Unit - 1.pptxUnit - 1.pptx
Unit - 1.pptx
 
chap 10 dbms.pptx
chap 10 dbms.pptxchap 10 dbms.pptx
chap 10 dbms.pptx
 
Aditi's Tech.pdf
Aditi's Tech.pdfAditi's Tech.pdf
Aditi's Tech.pdf
 
ds_mod1.pdf
ds_mod1.pdfds_mod1.pdf
ds_mod1.pdf
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
 

Recently uploaded

Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdfIGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
Amin Marwan
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Leena Ghag-Sakpal
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
Chevonnese Chevers Whyte, MBA, B.Sc.
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdfIGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 

chap 9 dbms.ppt

  • 1. Chapter Outline 9.1 General Constraints as Assertions 9.2 Views in SQL 9.3 Database Programming 9.4 Embedded SQL 9.5 Functions Calls, SQL/CLI 9.6 Stored Procedures, SQL/PSM 9.7 Summary
  • 2. Chapter Objectives • Specification of more general constraints via assertions • SQL facilities for defining views (virtual tables) • Various techniques for accessing and manipulating a database via programs in general-purpose languages (e.g., Java)
  • 3. Constraints as Assertions • General constraints: constraints that do not fit in the basic SQL categories (presented in chapter 8) • Mechanism: CREAT ASSERTION – components include: a constraint name, followed by CHECK, followed by a condition
  • 4. 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’’ CREAT ASSERTION SALARY_CONSTRAINT CHECK (NOT EXISTS (SELECT * FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D WHERE E.SALARY > M.SALARY AND E.DNO=D.NUMBER AND D.MGRSSN=M.SSN))
  • 5. Using General Assertions • 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
  • 6. SQL Triggers • Objective: to monitor a database and take action when a condition occurs • Triggers are expressed in a syntax similar to assertions and include the following: – event (e.g., an update operation) – condition – action (to be taken when the condition is satisfied)
  • 7. SQL Triggers: An 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 SALARY, SUPERVISOR_SSN ON EMPLOYEE FOR EACH ROW WHEN (NEW.SALARY> (SELECT SALARY FROM EMPLOYEE WHERE SSN=NEW.SUPERVISOR_SSN)) INFORM_SUPERVISOR (NEW.SUPERVISOR_SSN,NEW.SSN;
  • 8. Views in SQL • A view is a “virtual” table that is derived from other tables • Allows for limited update operations (since the table may not physically be stored) • Allows full query operations • A convenience for expressing certain operations
  • 9. What is a View? • In SQL, a VIEW is a virtual relation based on the result-set of a SELECT statement. • A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. In some cases, we can modify a view and present the data as if the data were coming from a single table. • Syntax: CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition
  • 10. SQL – Relations, Tables & Views • When we say Relation, it could be a Table or a View. There are three kind of relations: 1. Stored relations tables We sometimes use the term “base relation” or “base table” 2. Virtual relations views 3. Temporary results
  • 11. SQL – Create View • Example: Create a view with title and year and made by Paramount studio. Movie (title, year, length, inColor, studioName, producerC#) CREATE VIEW ParamountMovie AS SELECT title,year FROM Movie WHERE studioName = ‘Paramount’;
  • 12. SQL – Querying View • A view could be used from inside a query, a stored procedure, or from inside another view. By adding functions, joins, etc., to a view, it allows us to present exactly the data we want to the user. SELECT title FROM ParamountMovie WHERE year = ‘1979’; • Have same result as SELECT title FROM Movie WHERE studioName = ‘Paramount’ AND year = ‘1979’; View Table
  • 13. SQL - Querying View con’t • Query involving both view and table SELECT DISTINCT starName FROM ParamountMovie, StarsIn WHERE title = movieTitle AND year = movieYear; Table View
  • 14. SQL - Querying View example Movie (title, year, length, inColor, studioName, producerC#) MovieExec (name, address, cert#, netWorth) CREATE VIEW MovieProd AS SELECT title, name FROM Movie, MovieExec WHERE producerC# = cert#; SELECT name FROM MovieProd WHERE title = ‘Gone With the Wind’; • Same result as query from tables SELECT name FROM Movie, MovieExec WHERE producerC# = cert# AND title = ‘The War Of the World’;
  • 15. SQL - Renaming Attributes in View • Sometime, we might want to distinguish attributes by giving the different name. CREATE VIEW MovieProd (movieTitle, prodName) AS SELECT title, name FROM Movie, MovieExec WHERE producerC# = cert#;
  • 16. SQL - Modifying View When we modify a view, we actually modify a table through a view. Many views are not updateable. Here are rules have been defined in SQL for updateable views: • selecting (SELECT not SELECT DISTINCT) some attributes from one relation R (which may itself be an updateable view)  The WHERE clause must not involve R in a subquery.  The list in the SELECT clause must include enough attributes that will allow us to insert tuples into the view as well as table. All other attributes will be filled out with NULL or the proper default values.
  • 17. SQL – Modifying View (INSERT) INSERT INTO ParamountMovie VALUES (‘Star Trek’, 1979); To make the view ParamountMovie updateable, we need to add attribute studioName to it’s SELECT clause because it makes more sense if the studioName is Paramount instead of NULL. CREATE VIEW ParamountMovie AS SELECT studioName, title, year FROM Movie WHERE studioName = ‘Paramount’; Then INSERT INTO ParamountMovie VALUES (‘Paramount’, ‘Star Trek’, 1979); Title year length inColor studioName producerC# ‘Star Trek’ 1979 0 NULL ‘Paramount’ NULL
  • 18. SQL - Modifying View (DELETE) • Suppose we wish to delete all movies with “Trek” in their title from the updateable view ParamountMovie. DELETE FROM ParamountMovie WHERE title LIKE ‘%Trek%’; It is turned into the base table delete DELETE FROM Movie WHERE title LIKE ‘%Trek%’ AND studioName = ‘Paramount’;
  • 19. SQL - Modifying View (UPDATE) • UPDATE from an updateable view UPDATE ParamountMovie SET year = 1979 WHERE title = ‘Star Trek the Movie’; It is turned into the base table update UPDATE Movie SET year = 1979 WHERE title = ‘Star Trek the Movie’ AND studioName = ‘Paramount’;
  • 20. 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
  • 21. SQL Views: An Example • Specify a different WORKS_ON table CREATE TABLE WORKS_ON_NEW AS SELECT FNAME, LNAME, PNAME, HOURS FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER GROUP BY PNAME;
  • 22. Using a Virtual Table • We can specify SQL queries on a newly create table (view): SELECT FNAME, LNAME FROM WORKS_ON_NEW WHERE PNAME=‘Seena’; • When no longer needed, a view can be dropped: DROP WORKS_ON_NEW;
  • 23. Efficient View Implementation • Query modification: present the view query in terms of a query on the underlying base tables – disadvantage: inefficient for views defined via complex queries (especially if additional queries are to be applied to the view within a short time period)
  • 24. Efficient View Implementation • View materialization: involves physically creating and keeping a temporary table – assumption: other queries on the view will follow – concerns: maintaining correspondence between the base table and the view when the base table is updated – strategy: incremental update
  • 25. View Update • Update on a single view without aggregate operations: 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 – not always possible
  • 26. Un-updatable Views • Views defined using groups and aggregate functions are not updateable • Views defined on multiple tables using joins are generally not updateable • WITH CHECK OPTION: must be added to the definition of a view if the view is to be updated – to allow check for updatability and to plan for an execution strategy
  • 27. Database Programming • Objective: to access a database from an application program (as opposed to interactive interfaces) • Why? An interactive interface is convenient but not sufficient; a majority of database operations are made thru application programs (nowadays thru web applications)
  • 28. Database Programming Approaches • Embedded commands: database commands are embedded in a general-purpose programming language • Library of database functions: available to the host language for database calls; known as an API • A brand new, full-fledged language (minimizes impedance mismatch)
  • 29. Impedance Mismatch • Incompatibilities between a host programming language and the database model, e.g., – type mismatch and incompatibilities; requires a new binding for each language – set vs. record-at-a-time processing • need special iterators to loop over query results and manipulate individual values
  • 30. 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 terminates the connection
  • 31. 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 and a matching END-EXEC (or semicolon) – shared variables (used in both languages) usually prefixed with a colon (:) in SQL
  • 32. Example: Variable Declaration in Language C • 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, SQLCODE, …; EXEC SQL END DECLARE SECTION;
  • 33. 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;
  • 34. Embedded SQL in C Programming Examples 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, …); else printf(“SSN does not exist: “, ssn); prompt(“More SSN? (1=yes, 0=no): “, loop); END-EXEC }
  • 35. Embedded SQL in C Programming Examples • A cursor (iterator) is needed to process multiple tuples • FETCH commands move the cursor to the next tuple • CLOSE CURSOR indicates that the processing of query results has been completed
  • 36. Dynamic SQL • Objective: executing new (not previously compiled) SQL statements at run-time – a program accepts SQL statements from the keyboard at run-time – a point-and-click operation translates to certain SQL query • Dynamic update is relatively simple; dynamic query can be complex – because the type and number of retrieved attributes are unknown at compile time
  • 37. Dynamic SQL: An Example EXEC SQL BEGIN DECLARE SECTION; varchar sqlupdatestring[256]; EXEC SQL END DECLARE SECTION; … prompt (“Enter update command:“, sqlupdatestring); EXEC SQL PREPARE sqlcommand FROM :sqlupdatestring; EXEC SQL EXECUTE sqlcommand;
  • 38. Embedded SQL in Java • SQLJ: a standard for embedding SQL in Java • An SQLJ translator converts SQL statements into Java (to be executed thru the JDBC interface) • Certain classes, e.g., java.sql have to be imported
  • 39. Java Database Connectivity • JDBC: SQL connection function calls for Java programming • A Java program with JDBC functions can access any relational DBMS that has a JDBC driver • JDBC allows a program to connect to several databases (known as data sources)
  • 40. Steps in JDBC Database Access 1. Import JDBC library (java.sql.*) 2. Load JDBC driver: Class.forname(“oracle.jdbc.driver.OracleDriver”) 3. Define appropriate variables 4. Create a connect object (via getConnection) 5. Create a statement object from the Statement class: 1. PreparedStatment 2. CallableStatement
  • 41. Steps in JDBC Database Access (continued) 6. Identify statement parameters (to be designated by question marks) 7. Bound parameters to program variables 8. Execute SQL statement (referenced by an object) via JDBC’s executeQuery 9. Process query results (returned in an object of type ResultSet) – ResultSet is a 2-dimentional table
  • 42. Embedded SQL in Java: An Example ssn = readEntry(“Enter a SSN: “); try { #sql{select FNAME< LNAME, ADDRESS, SALARY into :fname, :lname, :address, :salary from EMPLOYEE where SSN = :ssn}; } catch (SQLException se) { System.out.println(“SSN does not exist: “,+ssn); return; } System.out.println(fname+“ “+lname+… );
  • 43. Multiple Tuples in SQLJ • SQLJ supports two types of iterators: – named iterator: associated with a query result – positional iterator: lists only attribute types in a query result • A FETCH operation retrieves the next tuple in a query result: fetch iterator-variable into program-variable
  • 44. Database Programming with Functional Calls • Embedded SQL provides static database programming • API: dynamic database programming with a library of functions – advantage: no preprocessor needed (thus more flexible) – drawback: SQL syntax checks to be done at run- time
  • 45. SQL Call Level Interface • A part of the SQL standard • Provides easy access to several databases within the same program • Certain libraries (e.g., sqlcli.h for C) have to be installed and available • SQL statements are dynamically created and passed as string parameters in the calls
  • 46. Components of SQL/CLI • Environment record: keeps track of database connections • Connection record: keep tracks of info needed for a particular connection • Statement record: keeps track of info needed for one SQL statement • Description record: keeps track of tuples
  • 47. Steps in C and SQL/CLI Programming 1. Load SQL/CLI libraries 2. Declare record handle variables for the above components (called: SQLHSTMT, SQLHDBC, SQLHENV, SQLHDEC) 3. Set up an environment record using SQLAllocHandle 4. Set up a connection record using SQLAllocHandle 5. Set up a statement record using SQLAllocHandle
  • 48. Steps in C and SQL/CLI Programming (continued) 6. Prepare a statement using SQL/CLI function SQLPrepare 7. Bound parameters to program variables 8. Execute SQL statement via SQLExecute 9. Bound columns in a query to a C variable via SQLBindCol 10. Use SQLFetch to retrieve column values into C variables
  • 49. Database Stored Procedures • Persistent procedures/functions (modules) are stored locally and executed by the database server (as opposed to execution by clients) • Advantages: – if the procedure is needed by many applications, it can be invoked by any of them (thus reduce duplications) – execution by the server reduces communication costs – enhance the modeling power of views
  • 50. Stored Procedure Constructs • A stored procedure CREATE PROCEDURE procedure-name (params) local-declarations procedure-body; • A stored function CREATE FUNCTION fun-name (params) RETRUNS return-type local-declarations function-body; • Calling a procedure or function CALL procedure-name/fun-name (arguments);
  • 51. SQL Persistent Stored Modules • 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
  • 52. SQL/PSM: An 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;
  • 53. Summary • Assertions provide a means to specify additional constraints • Triggers are a special kind of assertions; they define actions to be taken when certain conditions occur • Views are a convenient means for creating temporary (virtual) tables
  • 54. Summary (continued) • A database may be accessed via an interactive database • Most often, however, data in a database is manipulate via application programs • Several methods of database programming: – embedded SQL – dynamic SQL – stored procedure and function