SlideShare a Scribd company logo
1 of 5
Download to read offline
Database System Sunita M. Dol
Page 1
HANDOUT#08
Aim:
Implement queries on embedded SQL, functions, procedures and triggers
Theory:
Embedded SQL
The SQL standard defines embeddings of SQL in a variety of programming languages such as C,
Java, and Cobol. A language to which SQL queries are embedded is referred to as a host
language, and the SQL structures permitted in the host language comprise embedded SQL.
The basic form of these languages follows that of the System R embedding of SQL into PL/I.
EXEC SQL statement is used to identify embedded SQL request to the preprocessor
EXEC SQL <embedded SQL statement > END_EXEC
Note: this varies by language (for example, the Java embedding uses # SQL { …. }; )
Example: From within a host language, find the names and cities of customers with more than
the variable amount dollars in some account.
EXEC SQL
declare c cursor for
select depositor.customer_name, customer_city
from depositor, customer, account
where depositor.customer_name = customer.customer_name
and depositor account_number = account.account_number
and account.balance > :amount
END_EXEC
The open statement causes the query to be evaluated
EXEC SQL open c END_EXEC
The fetch statement causes the values of one tuple in the query result to be placed on host
language variables.
EXEC SQL fetch c into :cn, :cc END_EXEC
Repeated calls to fetch get successive tuples in the query result
A variable called SQLSTATE in the SQL communication area (SQLCA) gets set to ‘02000’ to
indicate no more data is available
The close statement causes the database system to delete the temporary relation that holds the
result of the query.
EXEC SQL close c END_EXEC
Database System Sunita M. Dol
Page 2
Note: above details vary with language. For example, the Java embedding defines Java iterators
to step through result tuples.
Functions and Procedures
SQL:1999 supports functions and procedures. Functions/procedures can be written in SQL itself,
or in an external programming language. Functions are particularly useful with specialized data
types such as images and geometric objects.
Example: functions to check if polygons overlap, or to compare images for similarity.
Some database systems support table-valued functions, which can return a relation as a result
SQL:1999 also supports a rich set of imperative constructs, including Loops, if-then-else,
assignment. Many databases have proprietary procedural extensions to SQL that differ from
SQL:1999
Example: Define a function that, given the name of a customer, returns the count of the number
of accounts owned by the customer.
create function account_count (customer_name varchar(20))
returns integer
begin
declare a_count integer;
select count (* ) into a_count
from depositor
where depositor.customer_name = customer_name
return a_count;
end
Example: Find the name and address of each customer that has more than one account.
select customer_name, customer_street, customer_city
from customer
where account_count (customer_name ) > 1
The account_count function could instead be written as procedure:
create procedure account_count_proc (in title varchar(20), out a_count integer)
begin
select count(author) into a_count
from depositor
where depositor.customer_name = account_count_proc.customer_name
end
Procedures can be invoked either from an SQL procedure or from embedded SQL, using the call
statement.
Database System Sunita M. Dol
Page 3
declare a_count integer;
call account_count_proc( ‘Smith’, a_count);
Procedures and functions can be invoked also from dynamic SQL
SQL:1999 allows more than one function/procedure of the same name (called name
overloading), as long as the number of
arguments differ, or at least the types of the arguments differ.
While and repeat statements:
declare n integer default 0;
while n < 10 do
set n = n + 1
end while
repeat
set n = n – 1
until n = 0
end repeat
For loop:
Example: find total of all balances at the Perryridge branch
declare n integer default 0;
for r as
select balance from account
where branch_name = ‘Perryridge’
do
set n = n + r.balance
end for
Conditional statements (if-then-else)
Example: To find sum of balances for each of three categories of accounts (with balance <1000,
>=1000 and <5000, >= 5000)
if r.balance < 1000
then set l = l + r.balance
elseif r.balance < 5000
then set m = m + r.balance
else set h = h + r.balance
end if
Triggers
Database System Sunita M. Dol
Page 4
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 (CREATES, ALTER, or DROP)
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated. 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
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions
• Creating Triggers
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
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
• {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.
• [ON table_name] − This specifies the name of the table associated with the trigger.
Database System Sunita M. Dol
Page 5
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.
Queries and Output:
Conclusion:
Thus we implemented the queries on
• Embedded SQL
• Functions and Procedures
• Triggers
References:
• Database system concepts by Abraham Silberschatz, Henry F. Korth, S. Sudarshan
(McGraw Hill International Edition) sixth edition.
• Database system concepts by Abraham Silberschatz, Henry F. Korth, S. Sudarshan
(McGraw Hill International Edition) fifth edition.
• http://codex.cs.yale.edu/avi/db-book/db4/slide-dir/
• http://codex.cs.yale.edu/avi/db-book/db5/slide-dir/
• http://codex.cs.yale.edu/avi/db-book/db6/slide-dir/

More Related Content

What's hot (19)

Sql commands
Sql commandsSql commands
Sql commands
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
SQL commands
SQL commandsSQL commands
SQL commands
 
Integrity and security
Integrity and securityIntegrity and security
Integrity and security
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Database queries
Database queriesDatabase queries
Database queries
 
12 SQL
12 SQL12 SQL
12 SQL
 
Sql.pptx
Sql.pptxSql.pptx
Sql.pptx
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
ch3
ch3ch3
ch3
 
Sql commands
Sql commandsSql commands
Sql commands
 
Dbms ii mca-ch7-sql-2013
Dbms ii mca-ch7-sql-2013Dbms ii mca-ch7-sql-2013
Dbms ii mca-ch7-sql-2013
 
Database Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and deleteDatabase Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and delete
 
Chapter8 my sql revision tour
Chapter8 my sql revision tourChapter8 my sql revision tour
Chapter8 my sql revision tour
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Sql operator
Sql operatorSql operator
Sql operator
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
6. Integrity and Security in DBMS
6. Integrity and Security in DBMS6. Integrity and Security in DBMS
6. Integrity and Security in DBMS
 

Similar to Assignment#08

Similar to Assignment#08 (20)

PLSQL.pptx
PLSQL.pptxPLSQL.pptx
PLSQL.pptx
 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3
 
Unit 3
Unit 3Unit 3
Unit 3
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
PLSQL (1).ppt
PLSQL (1).pptPLSQL (1).ppt
PLSQL (1).ppt
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 
Module04
Module04Module04
Module04
 
Sql
SqlSql
Sql
 
SQl
SQlSQl
SQl
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
Module02
Module02Module02
Module02
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
PLSQL
PLSQLPLSQL
PLSQL
 
Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01
 
stored.ppt
stored.pptstored.ppt
stored.ppt
 

More from Sunita Milind Dol (20)

9.Joins.pdf
9.Joins.pdf9.Joins.pdf
9.Joins.pdf
 
8.Views.pdf
8.Views.pdf8.Views.pdf
8.Views.pdf
 
7. Nested Subqueries.pdf
7. Nested Subqueries.pdf7. Nested Subqueries.pdf
7. Nested Subqueries.pdf
 
6. Aggregate Functions.pdf
6. Aggregate Functions.pdf6. Aggregate Functions.pdf
6. Aggregate Functions.pdf
 
5. Basic Structure of SQL Queries.pdf
5. Basic Structure of SQL Queries.pdf5. Basic Structure of SQL Queries.pdf
5. Basic Structure of SQL Queries.pdf
 
4. DML.pdf
4. DML.pdf4. DML.pdf
4. DML.pdf
 
3. DDL.pdf
3. DDL.pdf3. DDL.pdf
3. DDL.pdf
 
2. SQL Introduction.pdf
2. SQL Introduction.pdf2. SQL Introduction.pdf
2. SQL Introduction.pdf
 
1. University Example.pdf
1. University Example.pdf1. University Example.pdf
1. University Example.pdf
 
Assignment12
Assignment12Assignment12
Assignment12
 
Assignment11
Assignment11Assignment11
Assignment11
 
Assignment10
Assignment10Assignment10
Assignment10
 
Assignment9
Assignment9Assignment9
Assignment9
 
Assignment8
Assignment8Assignment8
Assignment8
 
Assignment7
Assignment7Assignment7
Assignment7
 
Assignment6
Assignment6Assignment6
Assignment6
 
Assignment5
Assignment5Assignment5
Assignment5
 
Assignment4
Assignment4Assignment4
Assignment4
 
Assignment3
Assignment3Assignment3
Assignment3
 
Assignment2
Assignment2Assignment2
Assignment2
 

Recently uploaded

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 

Recently uploaded (20)

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 

Assignment#08

  • 1. Database System Sunita M. Dol Page 1 HANDOUT#08 Aim: Implement queries on embedded SQL, functions, procedures and triggers Theory: Embedded SQL The SQL standard defines embeddings of SQL in a variety of programming languages such as C, Java, and Cobol. A language to which SQL queries are embedded is referred to as a host language, and the SQL structures permitted in the host language comprise embedded SQL. The basic form of these languages follows that of the System R embedding of SQL into PL/I. EXEC SQL statement is used to identify embedded SQL request to the preprocessor EXEC SQL <embedded SQL statement > END_EXEC Note: this varies by language (for example, the Java embedding uses # SQL { …. }; ) Example: From within a host language, find the names and cities of customers with more than the variable amount dollars in some account. EXEC SQL declare c cursor for select depositor.customer_name, customer_city from depositor, customer, account where depositor.customer_name = customer.customer_name and depositor account_number = account.account_number and account.balance > :amount END_EXEC The open statement causes the query to be evaluated EXEC SQL open c END_EXEC The fetch statement causes the values of one tuple in the query result to be placed on host language variables. EXEC SQL fetch c into :cn, :cc END_EXEC Repeated calls to fetch get successive tuples in the query result A variable called SQLSTATE in the SQL communication area (SQLCA) gets set to ‘02000’ to indicate no more data is available The close statement causes the database system to delete the temporary relation that holds the result of the query. EXEC SQL close c END_EXEC
  • 2. Database System Sunita M. Dol Page 2 Note: above details vary with language. For example, the Java embedding defines Java iterators to step through result tuples. Functions and Procedures SQL:1999 supports functions and procedures. Functions/procedures can be written in SQL itself, or in an external programming language. Functions are particularly useful with specialized data types such as images and geometric objects. Example: functions to check if polygons overlap, or to compare images for similarity. Some database systems support table-valued functions, which can return a relation as a result SQL:1999 also supports a rich set of imperative constructs, including Loops, if-then-else, assignment. Many databases have proprietary procedural extensions to SQL that differ from SQL:1999 Example: Define a function that, given the name of a customer, returns the count of the number of accounts owned by the customer. create function account_count (customer_name varchar(20)) returns integer begin declare a_count integer; select count (* ) into a_count from depositor where depositor.customer_name = customer_name return a_count; end Example: Find the name and address of each customer that has more than one account. select customer_name, customer_street, customer_city from customer where account_count (customer_name ) > 1 The account_count function could instead be written as procedure: create procedure account_count_proc (in title varchar(20), out a_count integer) begin select count(author) into a_count from depositor where depositor.customer_name = account_count_proc.customer_name end Procedures can be invoked either from an SQL procedure or from embedded SQL, using the call statement.
  • 3. Database System Sunita M. Dol Page 3 declare a_count integer; call account_count_proc( ‘Smith’, a_count); Procedures and functions can be invoked also from dynamic SQL SQL:1999 allows more than one function/procedure of the same name (called name overloading), as long as the number of arguments differ, or at least the types of the arguments differ. While and repeat statements: declare n integer default 0; while n < 10 do set n = n + 1 end while repeat set n = n – 1 until n = 0 end repeat For loop: Example: find total of all balances at the Perryridge branch declare n integer default 0; for r as select balance from account where branch_name = ‘Perryridge’ do set n = n + r.balance end for Conditional statements (if-then-else) Example: To find sum of balances for each of three categories of accounts (with balance <1000, >=1000 and <5000, >= 5000) if r.balance < 1000 then set l = l + r.balance elseif r.balance < 5000 then set m = m + r.balance else set h = h + r.balance end if Triggers
  • 4. Database System Sunita M. Dol Page 4 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 (CREATES, ALTER, or DROP) • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN). Triggers can be defined on the table, view, schema, or database with which the event is associated. 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 • Synchronous replication of tables • Imposing security authorizations • Preventing invalid transactions • Creating Triggers 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 [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) DECLARE Declaration-statements BEGIN Executable-statements EXCEPTION Exception-handling-statements END; Where, • CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name. • {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. • [ON table_name] − This specifies the name of the table associated with the trigger.
  • 5. Database System Sunita M. Dol Page 5 • [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE. • [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger. • WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers. Queries and Output: Conclusion: Thus we implemented the queries on • Embedded SQL • Functions and Procedures • Triggers References: • Database system concepts by Abraham Silberschatz, Henry F. Korth, S. Sudarshan (McGraw Hill International Edition) sixth edition. • Database system concepts by Abraham Silberschatz, Henry F. Korth, S. Sudarshan (McGraw Hill International Edition) fifth edition. • http://codex.cs.yale.edu/avi/db-book/db4/slide-dir/ • http://codex.cs.yale.edu/avi/db-book/db5/slide-dir/ • http://codex.cs.yale.edu/avi/db-book/db6/slide-dir/