ADBMS Unit1 2
ADBMS Unit1 2
B.Sc.IT(Data Science)-Sem-3
ACID Properties
The transaction refers to a small unit of any given program that consists
of various low-level tasks. Every transaction in DBMS must maintain ACID
– A (Atomicity), C (Consistency), I (Isolation), D (Durability). One must
maintain ACID so as to ensure completeness, accuracy, and integrity of
data.
1. Atomicity
The property of atomicity states that we must treat any given transaction
as an atomic unit. It means that either all or none of its operations need
to be executed. One must ensure that there is no state in the database in
which a transaction happens to be left partially completed. One must
either define the states before or after the execution/failure/abortion of
the transaction.
2. Consistency
The property of consistency states that the database must always remain
in a consistent state after any transaction. Thus, a transaction must never
have any damaging effect on the data and information that resides in the
database. In case, before the execution of a transaction, the database
happens to be in a consistent state, then it has to remain consistent even
after the transaction gets executed.
3. Durability
The property of durability states that any given database must be durable
enough to all of its latest updates, and it must happen even if the system
suddenly restarts or fails. The database would hold the modified data in
case a transaction updates and commits some chunk of information in the
database. In case a transaction commits and yet the system fails before we
write the data on the disk, then the information would be actually updated
after the system springs back into action.
4. Isolation
The property of isolation states that when multiple transactions are being
simultaneously executed and in parallel in a database system, then the
carrying out and execution of the transaction would occur as if it is the
only transaction that exists in the system. None of the transactions would
affect any other transaction’s existence.
States of Transaction
Active state
o The active state is the first state of every transaction. In this state,
the transaction is being executed.
o For example: Insertion or deletion or updating a record is done here.
But all the records are still not saved to the database.
Partially committed
o In the partially committed state, a transaction executes its final
operation, but the data is still not saved to the database.
o In the total mark calculation example, a final display of the total
marks step is executed in this state.
Committed
Failed state
o If any of the checks made by the database recovery system fails, then
the transaction is said to be in the failed state.
o In the example of total mark calculation, if the database is not able
to fire a query to fetch the marks, then the transaction will fail to
execute.
Aborted
o If any of the checks fail and the transaction has reached a failed state
then the database recovery system will make sure that the database
is in its previous consistent state. If not then it will abort or roll back
the transaction to bring the database into a consistent state.
o If the transaction fails in the middle of the transaction then before
executing the transaction, all the executed transactions are rolled
back to its consistent state.
o After aborting the transaction, the database recovery module will
select one of the two operations:
1. Re-start the transaction
2. Kill the transaction
Recovery
Let's assume there is a transaction to modify the City of a student. The following logs
are written for this transaction.
Checkpoint
o The checkpoint is a type of mechanism where all the previous logs are removed from
the system and permanently stored in the storage disk.
o The checkpoint is like a bookmark. While the execution of the transaction, such
checkpoints are marked, and the transaction is executed then using the steps of the
transaction, the log files will be created.
o When it reaches to the checkpoint, then the transaction will be updated into the
database, and till that point, the entire log file will be removed from the file. Then the
log file is updated with the new step of transaction till next checkpoint and so on.
o The checkpoint is used to declare a point before which the DBMS was in the consistent
state, and all transactions were committed.
o Phase- 2nd–
o The Second phase started as the response abort T or commit T receives
by the coordinator(Ci) from all the sites that are collaboratively executing
the transaction T. However, it is possible that some site fails to respond; it
may be down, or it has been disconnected by the network. In that case, after
a suitable timeout period will be given, after that time it will treat the site as if
it had sent abort T. The fate of the transaction depends upon the following
points:
o a) If the coordinator receives ready T from all the participating sites of T, then
it decides to commit T. Then, the coordinator writes on its site log
record <Commit T> and sends a message commit T to all the sites involved
in T.
o b) If a site receives a commit T message, it commits the component of T at
that site, and write it in log records <Commit T>.
o c) If a site receives the message abort T, it aborts T and writes the log
record <Abort T>.
o d) However, if the coordinator has received abort T from one or more sites, it
logs <Abort T> at its site and then sends abort T messages to all sites
involved in transaction T.
o
o Messaging in Phase- 2nd
o Disadvantages:
o a) The major disadvantage of the Two-phase commit protocol is faced when
the Coordinator site failure may result in blocking, so a decision either to
commit or abort Transaction(T) may have to be postponed until coordinator
recovers.
o b) Blocking Problem: Consider a scenario, if a Transaction(T) holds locks
on data-items of active sites, but amid the execution, if the coordinator fails
and the active sites keep no additional log-record except <readt
T> like <abort> or <commit>. So, it becomes impossible to determine what
decision has been made(whether to <commit> /<abort>). So, In that case,
the final decision is delayed until the Coordinator is restored or fixed. In some
cases, this may take a day or long hours to restore and during this time period,
the locked data items remain inaccessible for other transactions(Ti). This
problem is known as Blocking Problem.
00:00/04:28
Consider the below diagram where two transactions TX and TY, are performed on
the same account A where the balance of account A is $300.
o At time t1, transaction TX reads the value of account A, i.e., $300 (only read).
o At time t2, transaction TX deducts $50 from account A that becomes $250 (only
deducted and not updated/write).
o Alternately, at time t3, transaction TY reads the value of account A that will be $300
only because TX didn't update the value yet.
o At time t4, transaction TY adds $100 to account A that becomes $400 (only added but
not updated/write).
o At time t6, transaction TX writes the value of account A that will be updated as $250
only, as TY didn't update the value yet.
o Similarly, at time t7, transaction TY writes the values of account A, so it will write as
done at time t4 that will be $400. It means the value written by TX is lost, i.e., $250 is
lost.
For example:
For example:
Consider two transactions, TX and TY, performing the read/write operations on
account A, having an available balance = $300. The diagram is shown below:
o At time t1, transaction TX reads the value from account A, i.e., $300.
o At time t2, transaction TY reads the value from account A, i.e., $300.
o At time t3, transaction TY updates the value of account A by adding $100 to the
available balance, and then it becomes $400.
o At time t4, transaction TY writes the updated value, i.e., $400.
o After that, at time t5, transaction TX reads the available value of account A, and that will
be read as $400.
o It means that within the same transaction TX, it reads two different values of account A,
i.e., $ 300 initially, and after updation made by transaction TY, it reads $400. It is an
unrepeatable read and is therefore known as the Unrepeatable read problem.
Thus, in order to maintain consistency in the database and avoid such problems that
take place in concurrent execution, management is needed, and that is where the
concept of Concurrency Control comes into role.
Locking
Lock guaranties exclusive use of data items to a current transaction. It first accesses
the data items by acquiring a lock, after completion of the transaction it releases the
lock.
Types of Locks
The types of locks are as follows −
1. Shared Lock [Transaction can read only the data item values]
It is also known as a Read-only lock. In a shared lock, the data item can only
read by the transaction.
It can be shared between the transactions because when the transaction holds
a
lock, then it can't update the data on the data item.
2. Exclusive Lock [Used for both read and write data item values]
In the exclusive lock, the data item can be both reads as well as written by
the transaction.
This lock is exclusive, and in this lock, multiple transactions do not modify
the same data simultaneously.
Growing phase: In the growing phase, a new lock on the data item may be acquired by
Shrinking phase: In the shrinking phase, existing lock held by the transaction may be
In the below example, if lock conversion is allowed then the following phase can
happen:
Deadlock in DBMS
A deadlock is a condition where two or more transactions are waiting indefinitely for
one another to give up locks. Deadlock is said to be one of the most feared
complications in DBMS as no task ever gets finished and is in waiting state forever.
For example: In the student table, transaction T1 holds a lock on some rows and needs
to update some rows in the grade table. Simultaneously, transaction T2 holds locks on
some rows in the grade table and needs to update the rows in the Student table held
by Transaction T1.
Now, the main problem arises. Now Transaction T1 is waiting for T2 to release its lock
and similarly, transaction T2 is waiting for T1 to release its lock. All activities come to a
halt state and remain at a standstill. It will remain in a standstill until the DBMS detects
the deadlock and aborts one of the transactions.
Deadlock Avoidance
o When a database is stuck in a deadlock state, then it is better to avoid the database
rather than aborting or restating the database. This is a waste of time and resource.
o Deadlock avoidance mechanism is used to detect any deadlock situation in advance. A
method like "wait for graph" is used for detecting the deadlock situation but this
method is suitable only for the smaller database. For the larger database, deadlock
prevention method can be used.
Deadlock Detection
In a database, when a transaction waits indefinitely to obtain a lock, then the DBMS
should detect whether the transaction is involved in a deadlock or not. The lock
manager maintains a Wait for the graph to detect the deadlock cycle in the database.
Deadlock Prevention
o Deadlock prevention method is suitable for a large database. If the resources are
allocated in such a way that deadlock never occurs, then the deadlock can be
prevented.
o The Database management system analyzes the operations of the transaction whether
they can create a deadlock situation or not. If they do, then the DBMS never allowed
that transaction to be executed.
Wait-Die scheme
In this scheme, if a transaction requests for a resource which is already held with a
conflicting lock by another transaction then the DBMS simply checks the timestamp of
both transactions. It allows the older transaction to wait until the resource is available
for execution.
Let's assume there are two transactions Ti and Tj and let TS(T) is a timestamp of any
transaction T. If T2 holds a lock by some other transaction and T1 is requesting for
resources held by T2 then the following actions are performed by DBMS:
1. Check if TS(Ti) < TS(Tj) - If Ti is the older transaction and Tj has held some resource,
then Ti is allowed to wait until the data-item is available for execution. That means if
the older transaction is waiting for a resource which is locked by the younger
transaction, then the older transaction is allowed to wait for resource until it is available.
2. Check if TS(Ti) < TS(Tj) - If Ti is older transaction and has held some resource and if Tj
is waiting for it, then Tj is killed and restarted later with the random delay but with the
same timestamp.
What is Encryption?
Encryption helps us to secure data that we send, receive, and store. It can
consist text messages saved on our cell-phone, logs stored on our fitness
watch, and details of banking sent by your online account.
It is the way that can climb readable words so that the individual who has the
secret access code, or decryption key can easily read it. For diplomatic
information to help in providing data security.
The cipher text is converted back to the real form when the calculated recipient
accesses the message which is known as decryption.
"Secret" encryption key, a lining up of algorithms that climbed and unscramble
info. back to a readable type, must be worked by both the sender and the
receiver to get the code.
ACCESS CONTROL:
A database for an enterprise contains a great deal of information and usually has several
groups of users. Most users need to access only a small part of the database to carry out
their tasks.
User’s unrestricted access to all the data can be undesirable, and a DBMS should provide
to control access to data .A DBMS offers two main approaches to access control.
Discretionary access control is based on the concept of access rights, or privileges, and
mechanisms for giving users such privileges. A privilege allows a user to access Borne data
object (e.g., to read or Modify). A user, who creates a database object such as a table or a
vie\v automatically, gets all applicable privileges on that object.
Mandatory access control is based on system wide policies that cannot be changed by
individual users. In this approach each databal.'3e object is assigned a security class, each
user is assigned clearance for a security class, and rules are imposed on reading and writing
of database objects by users.
SQL supports discretionary access control through the GRANT and REVOKE commands.
The GRANT command gives users privileges to base tables and views. The syntax of this
command is as follows
For our purposes object is either a base table or a views. Several privileges can be
specified,including these:
SELECT: The right to access (read) all columns of the table specified as the object,
INSERT( column-name): The right to insert rows with (non-null or non default) values in
the column of the table named as object. If this right is to be granted with respect to all
columns, including columns that might be added later, we can simply use INSERT. The
privileges UPDATE( column name) and UPDATE are similar.
DELETE: The right to delete rows from the table named as object.
REFERENCES(column-name): The right to define foreign keys (in other tables) that
refer to the specified column of the table object. REFERENCES without a column name
specified denotes this right with respect to all columns, including any that are added later.
The privileges held by the creator of a view change over time as he or she gains or loses
privileges on the underlying tables. If the creator loses a privilege held 'with the grant
option,
users who where given that privilege on the view lose it as well. 'There are some subtle
aspects to the GRANT and REVOKE commands when they involve views or integrity
constraints. We
1) A view may be dropped because a SELECT privilege is revoked from the user who
2) If the creator of a view gains additional privileges on the underlying tables, he or she
3) The distinction between the REFERENCES and SELECT privileges are important.
The popular model for mandatory access control is described in terms of objects (e.g.,
tables, views, rows, columns), subjects (e.g., users,programs), security classes, and
clearances.
Each database object is assigned a security class, and each subject is assigned clearance
for security class; we denote the class of an object or subject A as class(A).
The model imposes two restrictions on all reads and writes of database objects:
1) Simple Security Property: Subject S is allowed to read object 0 only if class(8) > class
(()). For example, a user with TS clearance can read a table with C clearance, but a user
2) *-Property: Subject S is allowed to write object 0 only if class(S) <class (O). For
example, a user with S clearance can write only objects with S or TS classification.
Distributed Database:
A distributed database is a collection of multiple interconnected databases, which are
spread physically across various locations that communicate via a computer network.
What is PL/SQL
PL/SQL is a block structured language. The programs of PL/SQL are logical blocks
that can contain any number of nested sub-blocks. Pl/SQL stands for "Procedural
Language extension of SQL" that is used in Oracle. PL/SQL is integrated with Oracle
database (since version 7). The functionalities of PL/SQL usually extended after each
release of Oracle database. Although PL/SQL is closely integrated with SQL language,
yet it adds some programming constraints that are not available in SQL.
PL/SQL Advantages
▪ Procedural language support PL/SQL is a development tools not only for data
manipulation futures but also provide the conditional checking, looping or
branching operations same as like other programming language.
▪ Error handling PL/SQL is dealing with error handling, It's permits the smart
way handling the errors and giving user friendly error messages, when the
errors are encountered.
▪ Declare variable PL/SQL gives you control to declare variables and access
them within the block. The declared variables can be used at the time
of query processing.
Variables and Constants: In this block, declare and initialize variables (and constants).
You must have to declare variables and constants in the declarative block before
referencing them in a procedural statement.
Declare Variables and Assigning values: You can define a variable name, data type of a
variable, and its size. Date type can be CHAR, VARCHAR2, DATE, NUMBER, INT, or
any other.
BEGIN
BEGIN block is a procedural statement block which will implement the actual
programming logic. This section contains conditional statements (if...else), looping
statements (for, while) and Branching Statements (goto), etc.
EXCEPTION
PL/SQL easily detects a user-defined or predefined error condition. PL/SQL is famous
for smartly handling errors by giving suitable user-friendly messages. Errors can be
rise due to the wrong syntax, bad logical, or not passing validation rules.
You can also define exception in your declarative block, and later you can execute it
by RAISE statement.
Note
1. BEGIN block, and END; keyword are compulsory of any PL/SQL program.
2. Whereas, the DECLARE and EXCEPTION block are optional.
PL/SQL Literals
Literals are the explicit numeric, character, string or boolean values which are not
represented by an identifier. For example: TRUE, NULL, etc. are all literals of type
boolean. PL/SQL literals are case-sensitive. There are following kinds of literals in
PL/SQL:
o Numeric Literals
o Character Literals
o String Literals
o BOOLEAN Literals
Literals Examples
Numeric 75125, 3568, 33.3333333 etc.
Character 'A' '%' '9' ' ' 'z' '('
String Hello
Boolean TRUE, FALSE, NULL etc.
• Number
• Boolean
• Character
• Datetime
PL/SQL Variables
A variable is a meaningful name which facilitates a programmer to store data
temporarily during the execution of code. It helps you to manipulate data in PL/SQL
programs. It is nothing except a name given to a storage area. Each variable in the
PL/SQL has a specific data type which defines the size and layout of the variable's
memory.
Here, variable_name is a valid identifier in PL/SQL and datatype must be valid PL/SQL
data type. A data type with size, scale or precision limit is called a constrained
declaration. The constrained declaration needs less memory than unconstrained
declaration.
Example:
Radius Number := 5;
Date_of_birth date;
1. counter binary_integer := 0;
1. DECLARE
2. a integer := 30;
3. b integer := 40;
4. c integer;
5. f real;
6. BEGIN
7. c := a + b;
8. dbms_output.put_line('Value of c: ' || c);
9. f := 100.0/3.0;
10. dbms_output.put_line('Value of f: ' || f);
11. END;
Value of c: 70
Value of f: 33.333333333333333333
PL/SQL Comment>
PL/SQL Comments you can write single line comments or either multiple line
comments,
Comment Syntax
SQL>-- Single Line Comment
SQL>/* Multiline Comment line 1
Multiline Comment line2 */
PL/SQL IF statement check condition and transfer the execution flow on that
matched block depending on a condition. IF statement execute or skip a sequence of
one or more statements. PL/SQL IF statement four different type,
1. IF THEN Statement
2. IF THEN ELSE Statement
3. IF THEN ELSIF Statement
4. Nested IF THEN ELSE Statement
IF THEN Statement
IF THEN Statement write in following syntax format:
IF ( condition ) THEN
statement
END IF;
Example
Example
Same as above example if condition not true then else part will execute.
DECLARE
no number := 14;
BEGIN
IF ( no = 11 ) THEN
DBMS_OUTPUT.PUT_LINE(no || ' is same');
ELSE
DBMS_OUTPUT.PUT_LINE(no || ' is not same');
END IF;
END;
/
Example
Example
Here check condition students gender male, if not male then finding the result using
nested IF THEN ELSE statement.
DECLARE
gender CHAR(10) := 'female';
result CHAR(20) := 'second';
BEGIN
IF ( gender = 'male' ) THEN
DBMS_OUTPUT.PUT_LINE('Gender Male Record Skip!');
ELSE
IF ( result = 'distinction' ) THEN
DBMS_OUTPUT.PUT_LINE('First Class with Distinction');
ELSIF ( result = 'first' ) THEN
DBMS_OUTPUT.PUT_LINE('First Class');
ELSIF ( result = 'second' ) THEN
DBMS_OUTPUT.PUT_LINE('Second Class');
ELSIF ( result = 'third' ) THEN
DBMS_OUTPUT.PUT_LINE('Third Class');
ELSE
DBMS_OUTPUT.PUT_LINE('Fail');
END IF;
END IF;
END;
/
PL/SQL Loop
PL/SQL Loop Basic Loop, FOR Loop, WHILE Loop repeat a number of block
statements in your PL/SQL program. Loop use when we have a block of statements
for required to repeatedly certain number of times. PL/SQL loop statements 3
different forms:
1. Basic LOOP
2. WHILE LOOP
3. FOR LOOP
Oracle recommended to write a label when use loop statement. It's benefit to
improve readability. label is not compulsory for execute loop. compiler does not
check to label defined or not. Define label before LOOP keyword and after END
LOOP keyword.
Basic LOOP
Basic LOOP write in following syntax format:
[ label_name ]LOOP
statement(s);
END LOOP [ label_name ];
Example
DECLARE
no NUMBER := 5;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ('Inside value: no = ' || no);
no := no -1;
IF no = 0 THEN
EXIT;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Outside loop end');
END;
/
Result
Inside value: no = 5
Inside value: no = 4
Inside value: no = 3
Inside value: no = 2
Inside value: no = 1
Outside loop end
WHILE LOOP
WHILE LOOP write in following syntax format:
[ label_name ] WHILE condition LOOP
statement(s);
END LOOP [ label_name ];
Example
DECLARE
no NUMBER := 0;
BEGIN
WHILE no < 10 LOOP
no := no + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('no is :' || no);
END;
/
Result
No is : 10
FOR LOOP
FOR LOOP write in following syntax format:
[ label_name ] FOR current_value IN [ REVERSE ] lower_value..upper_value LOOP
statement(s);
END LOOP [ label_name ];
Example
BEGIN
FOR no IN 1 .. 5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration : ' || no);
END LOOP;
END;
/
Result
Iteration : 1
Iteration : 2
Iteration : 3
Iteration : 4
Iteration : 5
GOTO Statement
GOTO statement unconditionally transfer program control. GOTO statement writing
syntax,
Syntax
GOTO code_name
-----------
-----------
<<code_name>>
-----------
-----------
Example
SQL>BEGIN
FOR i IN 1..5 LOOP
dbms_output.put_line(i);
IF i=4 THEN
GOTO label1;
END IF;
END LOOP;
<<label1>>
DBMS_OUTPUT.PUT_LINE('Row Filled');
END;
/
Result
1
2
3
4
Row Filled
PL/SQL Cursors
Oracle creates a memory area ,known as the context area ,for processing an SQL
statement ,which contains all the information needed for processing the statement;
A cursor is a pointer to this context area.PL/SQL controls the context area througha
cursor. A cursor holds the rows(one or more)returned by a SQL statement.The set of
You can name a cursor so that it could be referred to in a program to fetch and
process
Classification of CURSORS
Cursors can be classified as:
1. Implicit Cursor or Internal Cursor Manage for Oracle itself or internal process itself.
2. Explicit Cursor or User-defined Cursor Manage for user/programmer or external
processing.
Implicit Cursors
control the implicit cursors and the information in it. Whenever a DML
statement(INSERT,UPDATE and DELETE)is issued, an implicit cursor is associated with
this statement.For INSERT operations,the cursor holds the data that needs to be
inserted.For UPDATE and DELETE operations,the cursor identifies the rows that would
be affected. In PL/SQL,you can refer to the most recent implicit cursor as the SQL
cursor,which always has attributes such as%FOUND,%ISOPEN,%NOTFOUND,
and%ROWCOUNT.
%FOUND SQL%FOUND If SELECT statement return one or more rows or DML statement
(INSERT, UPDATE, DELETE) affect one or more rows
If affect return TRUE otherwise return FALSE.
If not execute SELECT or DML statement return NULL.
%NOTFOUND SQL%NOTFOUND If SELECT INTO statement return no rows and fire no_data_found
PL/SQL exception before you can check SQL%NOTFOUND.
If not affect the row return TRUE otherwise return FALSE.
%ROWCOUNT SQL%ROWCOUNT Return the number of rows affected by a SELECT statement or DML
statement (insert, update, delete).
If not execute SELECT or DML statement return NULL.
Syntax
cursor_attribute ::=
{
cursor_name |
cursor_variable_name |
:host_cursor_variable_name
}
% {FOUND | ISOPEN | NOTFOUND | ROWCOUNT}
Explanation
cursor_name cursor_name identifies the current scope which are previously declared.
cursor_variable_name cursor variable or parameter identifies the current scope which
are previously declared.
Now above employee information table update the employee name 'Saulin'
department 'Program Developer' update to 'Web Developer'.
Example
implicit_cursor.sql
SQL>set serveroutput on
SQL>edit implicit_cursor
BEGIN
UPDATE demo SET name=’dax’
WHERE id=1;
IF SQL%FOUND THEN
dbms_output.put_line('Updated - If Found');
END IF;
IF SQL%NOTFOUND THEN
dbms_output.put_line('NOT Updated - If NOT Found');
END IF;
IF SQL%ROWCOUNT>0 THEN
dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated');
ELSE
dbms_output.put_line('NO Rows Updated Found');
END;
/
Result
SQL>@implicit_cursor
Updated - If Found
1 Rows Updated
User itself to declare the cursor, open cursor to reserve the memory and populate
data, fetch the records from the active data set one at a time, apply logic and last
close the cursor.
You can not directly assign value to an explicit cursor variable you have to use
expression or create subprogram for assign value to explicit cursor variable.
Declaring the cursor defines the cursor withaname and the associated SELECT
statement.For example-
Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it.For example,we will open the
above defined cursor as follows-
OPEN c_customers;
Fetching the cursor involves accessing one row atatime.For example,we will fetch rows
from the-opened cursor as follows-
Closing the cursor means releasing the allocated memory.For example,we will close
the above opened cursor as follows-
CLOSE c_customers;
CURSOR c IS -- Define c,
SELECT * FROM emp_information; -- all row return type
3. Loop
Loop iterate until ROW not found. Once found loop exit control goes next
statement (outside loop).
Using FETCH statement you can fetch CURSOR data into explicit variable.
FETCH cursor_name INTO variable;
Example
explicit_cursor.sql
SQL>set serveroutput on
SQL>edit explicit_cursor
DECLARE
cursor c is select * from emp_information
where emp_name='bhavesh';
tmp emp_information%rowtype;
BEGIN
OPEN c;
Loop exit when c%NOTFOUND;
FETCH c into tmp;
update emp_information set tmp.emp_dept='Web Developer'
where tmp.emp_name='Saulin';
END Loop;
IF c%ROWCOUNT>0 THEN
dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated');
ELSE
dbms_output.put_line('NO Rows Updated Found');
END IF;
CLOSE c;
END;
/
Result
SQL>@explicit_cursor
1 Rows Updated
PL/SQL Parameterized cursor define only datatype of parameter and not need to
define it's length.
Default values is assigned to the Cursor parameters. and scope of the parameters are
locally.
Parameterized cursors are also saying static cursors that can passed parameter value
when cursor are opened.
Example
SQL>set serveroutput on
SQL>edit parameter_cursor_demo
DECLARE
cursor c(no number) is select * from emp_information
where emp_no = no;
tmp emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No: '||tmp.emp_no);
dbms_output.put_line('EMP_Name: '||tmp.emp_name);
dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
END Loop;
CLOSE c;
END;
/
Result
SQL>@parameter_cursor_demo
EMP_No: 4
EMP_Name: Zenia Sroll
EMP_Dept: Web Developer
EMP_Salary: 42k
The following illustrates the syntax of the cursor FOR LOOP statement:
1) record
The record is the name of the index that the cursor FOR LOOP statement declares
implicitly as a %ROWTYPE record variable of the type of the cursor.
The record variable is local to the cursor FOR LOOP statement. It means that you can
only reference it inside the loop, not outside. After the cursor FOR LOOP statement
execution ends, the record variable becomes undefined.
2) cursor_name
The cursor_name is the name of an explicit cursor that is not opened when the loop
starts.
Note that besides the cursor name, you can use a SELECT statement as shown below:
In this case, the cursor FOR LOOP declares, opens, fetches from, and closes an implicit
cursor. However, the implicit cursor is internal; therefore, you cannot reference it.
Note that Oracle Database automatically optimizes a cursor FOR LOOP to work
similarly to a BULK COLLECT query. Although your code looks as if it fetched one row at
a time, Oracle Database fetches multiple rows at a time and allows you to process
each row individually.
The following example declares an explicit cursor and uses it in the cursor FOR
LOOP statement.
DECLARE
CURSOR c_product
IS
SELECT
product_name, list_price
FROM
products
ORDER BY
list_price DESC;
BEGIN
FOR r_product IN c_product
LOOP
dbms_output.put_line( r_product.product_name || ': $' || r_product.list_price );
END LOOP;
END;
Code language: SQL (Structured Query Language) (sql)
In this example, the SELECT statement of the cursor retrieves data from
the products table. The FOR LOOP statement opened, fetched each row in the result set,
displayed the product information, and closed the cursor.
The following example is equivalent to the example above but uses a query in a
cursor FOR LOOP statement.
BEGIN
FOR r_product IN (
SELECT
product_name, list_price
FROM
products
ORDER BY list_price DESC
)
LOOP
dbms_output.put_line( r_product.product_name ||
': $' ||
r_product.list_price );
END LOOP;
END;