Unit 3
Unit 3
Department: BCA
Subject: Oracle PL/SQL
Faculty Name: Mr. Peeyush Sharma
UNIT -3
Integrity and Security: General considerations, Controls, Audit trail, Data encryption, Integrity rules,
Granting and Revoking privileges, SQL support Tools.
3. Describe the types of controls used in database systems (e.g., access, concurrency, and
inference controls).
Answer:
Database systems employ various control mechanisms to ensure data security, integrity, and
consistency. Key types of controls include:
• Access Controls:
These regulate who can access specific data and what operations they can
perform. Common models include:
• Discretionary Access Control (DAC): The owner of a data object determines
access permissions.
• Mandatory Access Control (MAC): Access is governed by system-wide
security policies, often based on security labels assigned to subjects and objects.
• Role-Based Access Control (RBAC): Permissions are assigned to roles, and
users are granted access by being assigned to specific roles.
• Concurrency Controls:
These manage simultaneous operations by multiple users or processes to prevent conflicts
and maintain data consistency. Techniques include:
• Lock-based protocols: Employ locks on data items to control concurrent access,
such as Two-Phase Locking (2PL), which ensures transactions acquire all
necessary locks before releasing any.
• Timestamp ordering: Transactions are assigned timestamps, and operations are
ordered based on these timestamps to resolve conflicts.
• Optimistic concurrency control: Transactions proceed without explicit locking,
and conflicts are detected and resolved at commit time, typically by rolling back
conflicting transactions.
• Inference Controls:
These prevent unauthorized users from deducing sensitive information by combining
permitted queries or statistical data, even if direct access to the sensitive data is
restricted. This is particularly relevant in statistical databases where users might infer
individual-level data from aggregate statistics. Techniques involve data perturbation, cell
suppression, or restricting query types.
12. How can Oracle secure sensitive information like passwords or account details?
Answer:
Oracle secures sensitive data like passwords and account details through a combination of
encryption, secure storage, and access control measures. This includes encrypting passwords
before storage, using strong hashing algorithms, implementing account lockout features, and
employing network encryption.
Here's a breakdown of Oracle's security measures:
1. Encryption:
• Password Encryption:
Oracle automatically encrypts passwords using AES (Advanced Encryption Standard)
before transmitting them across the network during authentication.
• Transparent Data Encryption (TDE):
TDE encrypts data at rest within the database, protecting it from unauthorized access even
if the storage media is compromised.
• Data Redaction:
Oracle Data Redaction can be used to mask sensitive data like credit card numbers or
social security numbers, either partially or completely, when displaying or accessing the
data.
2. Secure Storage:
• Hashing:
When a user creates or modifies a password, Oracle generates a cryptographic hash (or
digest) of the password and stores this hash instead of the plain text password.
• Secure External Password Store:
Using an Oracle wallet or a secure external password store to encrypt passwords before
storing them is recommended.
• Oracle Wallet:
This is a secure software container that stores authentication and signing credentials,
including passwords.
3. Access Control:
• Account Lockout:
Oracle provides an account lockout feature that locks a user's credentials after a certain
number of failed login attempts, preventing brute-force attacks.
• Network Encryption:
Oracle Advanced Security uses network encryption and SSL to protect data during
transmission.
• Strong Authentication:
Oracle recommends using strong authentication methods like Kerberos, token cards,
smart cards, or X.509 certificates for user authentication.
• User Profiles:
Database administrators can control password management policies through user profiles,
enabling control over password length, complexity, and other security parameters.
4. Other Security Practices:
• Patching:
Keeping the Oracle database and related software up-to-date with the latest security
patches is crucial.
• Monitoring:
Enable auditing and monitor for suspicious activities, such as unauthorized access
attempts, role changes, or password resets.
• Regular Rotation:
Regularly rotate API keys, authentication tokens, and service account passwords to
minimize the risk of unauthorized access.
13. What are the drawbacks of relying only on encryption for data security?
Answer:
Encryption is a powerful safeguard, but it’s not a complete solution on its own. If
organizations rely only on encryption for data security, several weaknesses can remain.
Here’s a detailed breakdown:
1. Key Management Challenges
• Single point of failure: If encryption keys are lost, data becomes permanently
inaccessible.
• Key compromise risk: If keys are stolen or mismanaged, encrypted data can be
decrypted instantly.
• Operational complexity: Rotating keys and securely distributing them is difficult at
scale.
2. No Protection Against Authorized Misuse
• Encryption doesn’t stop insiders with valid access: A DBA or application user with
decryption privileges can still read or copy sensitive data.
• Application-layer attacks still succeed: SQL injection or compromised credentials
bypass encryption because the database decrypts data for “legitimate” queries.
3. Data in Use Is Still Vulnerable
• Encryption protects data at rest or in transit — but once data is decrypted in memory
for processing, it can be stolen.
• RAM scraping or memory attacks can capture data after decryption.
4. Performance Overhead
• Higher CPU usage: Encrypting/decrypting large volumes of data can slow down
performance.
• Latency for critical transactions: Real-time encryption can impact response times,
especially without hardware acceleration.
5. Limited Coverage
• Metadata often remains unencrypted: Table names, schemas, and access patterns may
still reveal sensitive information.
• Not a substitute for access control: Encryption doesn’t decide who should have access
— it just obscures the data until it’s unlocked.
6. False Sense of Security
• Organizations may skip other protections: Thinking “we’re encrypted” can lead to
weaker authentication, poor patching, or no auditing.
• Regulatory compliance is broader: Encryption alone doesn’t meet full requirements for
GDPR, HIPAA, etc., which also demand logging, monitoring, and user accountability.
16. How are constraints used to enforce data integrity in Oracle SQL?
Answer:
Constraints in Oracle SQL are rules defined on table columns to enforce data integrity,
ensuring the accuracy, consistency, and validity of data within the database. They prevent the
entry of invalid data and maintain relationships between tables.
Here's how different types of constraints achieve this:
• NOT NULL Constraint:
Ensures that a column cannot contain a NULL value, guaranteeing that essential data is
always present.
• UNIQUE Constraint:
Guarantees that all values in a column or a set of columns are unique, preventing
duplicate entries. Oracle automatically creates a unique index to enforce this.
• PRIMARY KEY Constraint:
A combination of NOT NULL and UNIQUE. It uniquely identifies each row in a table
and serves as the primary identifier for records. Oracle automatically creates a unique
index for primary keys.
• FOREIGN KEY Constraint:
Enforces referential integrity by establishing a link between two tables. It ensures that
values in a foreign key column in the child table must match existing values in the
primary or unique key of the parent table, preventing orphaned records.
• CHECK Constraint:
Defines a condition that must be true for every row in a table. This allows for custom
business rules to be enforced, such as ensuring a numeric value falls within a specific
range or a string adheres to a particular format.
Enforcement Mechanisms:
• Automatic Validation:
When a DML (Data Manipulation Language) statement like INSERT, UPDATE,
or DELETE is executed, Oracle automatically checks if the operation violates any enabled
constraints.
• Transaction Rollback:
If a DML operation attempts to violate an enabled constraint, Oracle rolls back the entire
statement and returns an error, preventing the invalid data from being committed to the
database.
• Constraint States:
Constraints can be ENABLED or DISABLED. When ENABLED, they actively enforce
data rules. When DISABLED, they are not enforced, allowing data that might violate the
constraint to be entered (though this is generally discouraged for live
data). The VALIDATE and NOVALIDATE options control whether existing data is
checked when a constraint is enabled.
17. Write SQL commands to implement NOT NULL, UNIQUE, and CHECK constraints.
Answer:
SQL commands can be used to implement NOT NULL, UNIQUE, and CHECK constraints
during table creation or by altering an existing table.
1. NOT NULL Constraint:
This constraint ensures that a column cannot contain NULL values. During table creation.
Code
CREATE TABLE Employees (
EmployeeID INT NOT NULL,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Age INT
);
Adding to an existing column.
Code
ALTER TABLE Employees
ALTER COLUMN Age INT NOT NULL;
2. UNIQUE Constraint:
This constraint ensures that all values in a column (or a set of columns) are distinct. During
table creation.
Code
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(100) UNIQUE,
SKU VARCHAR(20) UNIQUE
);
Adding to an existing column.
Code
ALTER TABLE Products
ADD CONSTRAINT UQ_ProductName UNIQUE (ProductName);
3. CHECK Constraint:
This constraint limits the value range that can be placed in a column. During table creation
(column-level).
Code
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
Quantity INT CHECK (Quantity > 0)
);
During table creation (table-level).
Code
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Age INT,
CONSTRAINT CHK_Age CHECK (Age >= 18 AND Age <= 60)
);
Adding to an existing table.
Code
ALTER TABLE Orders
ADD CONSTRAINT CHK_Quantity CHECK (Quantity BETWEEN 1 AND 100);
18. Describe how foreign keys help maintain referential integrity.
Answer:
Foreign keys enforce referential integrity by ensuring that a foreign key value in one table
must exist as a primary key value in the related table. This prevents orphaned records (records
in the child table that refer to non-existent records in the parent table) and maintains
consistent relationships between tables.
Here's a more detailed explanation:
1. What are foreign keys?
A foreign key is a column or set of columns in one table that refers to the primary key (or a
unique key) of another table. This creates a link or relationship between the two tables.
2. What is referential integrity?
Referential integrity is a database concept that ensures the relationships between tables are
valid and consistent. It means that any value in a foreign key column must correspond to an
existing, valid record in the parent table.
3. How do foreign keys maintain referential integrity?
• Preventing orphaned records:
When a foreign key is defined, the database system enforces a rule that prevents the
deletion of a record in the parent table if there are related records (with matching foreign
key values) in the child table.
• Ensuring valid references:
Foreign keys also prevent the insertion or updating of foreign key values in the child table
if those values don't exist as primary key values in the parent table. This ensures that
every reference in the child table is to a valid record in the parent table.
4. Example:
Imagine a database with two tables: Customers and Orders. The Orders table has
a customer_id column that is a foreign key referencing the customer_id column in
the Customers table.
• Referential integrity in action:
If a customer record is deleted from the Customers table, the database will either:
• Prevent the deletion if there are any orders associated with that customer (using
RESTRICT).
• Delete the associated orders from the Orders table (using CASCADE).
• Set the customer_id in the Orders table to NULL for those orders (using SET
NULL).
• Enforcing valid references:
When adding a new order, the database will ensure that the customer_id in
the Orders table matches an existing customer_id in the Customers table.
5. Benefits of referential integrity:
• Data accuracy:
Prevents inconsistencies and errors that can arise from orphaned records or invalid
references.
• Data reliability:
Ensures that data across different tables is consistent and trustworthy.
• Simplified data management:
Makes it easier to query and analyze data because relationships are clearly defined and
enforced.
• Improved data integrity:
Prevents the database from becoming corrupted due to invalid relationships.
19. Explain the difference between system privileges and object privileges.
Answer:
System Privileges
• Allow users to perform actions on the database (not specific objects).
• Examples:
o CREATE SESSION – Connect to the database.
o CREATE TABLE – Create new tables.
o CREATE USER – Create new users.
o DROP TABLE – Delete tables.
Object Privileges
• Allow users to perform actions on specific objects (tables, views, sequences,
procedures).
• Examples:
o SELECT – Read data from a table or view.
o INSERT, UPDATE, DELETE – Modify table data.
o EXECUTE – Run a stored procedure.
o REFERENCES – Create foreign keys referencing another table.
20. How can you grant and revoke permissions in SQL? Provide syntax and examples.
Answer:
Granting Privileges
Use the GRANT statement to give privileges to users or roles.
Granting System Privileges
-- Granting system privileges
GRANT CREATE SESSION, CREATE TABLE TO peeyush;
-- Granting admin option (can pass the privilege to others)
GRANT CREATE USER TO admin_user WITH ADMIN OPTION;
Granting Object Privileges
-- Grant SELECT and INSERT on table to a user
GRANT SELECT, INSERT ON employees TO peeyush;
-- Allow another user to grant the same privileges further
GRANT UPDATE ON employees TO manager WITH GRANT OPTION;
Granting Privileges to Roles
Roles group privileges for easier management:
-- Create a role and grant privileges to it
CREATE ROLE hr_role;
GRANT CREATE SESSION, CREATE VIEW TO hr_role;
-- Grant the role to a user
GRANT hr_role TO peeyush;
Revoking Privileges
Use the REVOKE statement to remove privileges.
Revoking System Privileges
-- Remove CREATE TABLE privilege
REVOKE CREATE TABLE FROM peeyush;
Revoking Object Privileges
-- Remove SELECT privilege on a table
REVOKE SELECT ON employees FROM peeyush;
-- Remove a role from a user
REVOKE hr_role FROM peeyush;
21. What tools does Oracle provide to support database security and integrity?
Answer:
Oracle provides a layered set of tools and features that work together to ensure database
security (prevent unauthorized access) and data integrity (ensure accuracy and consistency
of data). These include command-line utilities, GUI tools, built-in database features, and
auditing mechanisms.
1. Administration Tools
Tool Role in Security and Integrity
Command-line tool to create users, grant/revoke privileges,
SQL*Plus
enforce constraints, and configure auditing.
Web-based GUI for centralized user management, privilege
Oracle Enterprise
assignment, security policy enforcement, and real-time
Manager (OEM)
monitoring.
22. Describe the role of SQL*Plus and Oracle Enterprise Manager in maintaining integrity
and security.
Answer:
Both SQL*Plus and Oracle Enterprise Manager (OEM) are key DBA tools in Oracle
environments, but they serve different purposes and complement each other. Here’s a clear
explanation of how each contributes to maintaining integrity and security:
1. SQL*Plus – Command-line control for direct administration
Role in Integrity and Security:
• Direct privilege management:
DBAs can use SQL*Plus to grant, revoke, or audit system and object privileges precisely
using SQL statements (e.g., GRANT CREATE SESSION TO user;).
• Data integrity enforcement:
SQL*Plus is used to define integrity constraints (PRIMARY KEY, FOREIGN KEY,
CHECK, UNIQUE) and to validate them (ALTER TABLE ... ENABLE CONSTRAINT;).
• Security configuration via scripts:
Password policies, account lockouts, and roles can be scripted and applied consistently.
• Auditing setup:
Auditing can be configured with AUDIT commands (e.g., AUDIT SELECT ON
employees BY ACCESS;) and verified through data dictionary views.
• Verification of changes:
SQL queries allow DBAs to inspect user privileges, roles, and system settings at a
granular level.
Key point: SQL*Plus provides precise, low-level, command-driven control — ideal for
scripting, automation, and direct security configuration.
2. Oracle Enterprise Manager (OEM) – GUI-based centralized administration
Role in Integrity and Security:
• Visual privilege and role management:
OEM lets DBAs assign/revoke privileges through an intuitive interface without writing
manual SQL.
• Database security policies:
Password complexity, expiration, and account lockout policies can be set graphically.
• Auditing and compliance monitoring:
OEM automatically collects and displays audit logs, user activity, and failed login
attempts in dashboards.
• Alerts and diagnostics:
Real-time alerts for suspicious activity, unauthorized changes, or policy violations help
maintain database integrity.
• User account management:
Administrators can create, lock, or drop users with a few clicks while OEM ensures
consistent enforcement of Oracle security best practices.
Key point: OEM provides centralized, visual monitoring and policy enforcement — ideal for
ongoing security oversight and compliance reporting.
23. How can a DBA use data dictionary views to monitor privileges and audit logs?
Answer:
A DBA in Oracle uses data dictionary views to check who has what privileges, verify role
assignments, and track audited actions. These views are prebuilt tables maintained by Oracle
that provide metadata about users, roles, privileges, and audit records. Here's how it’s
typically done:
1. Monitoring User and Role Privileges
Key Views for Privileges:
• DBA_USERS – Lists all database users and their default settings.
• DBA_ROLES – Shows all roles created in the database.
• DBA_SYS_PRIVS – Shows system privileges granted to users or roles (e.g.,
CREATE SESSION).
• DBA_TAB_PRIVS – Shows object-level privileges (SELECT, INSERT, UPDATE
on tables, views).
• DBA_ROLE_PRIVS – Shows which roles are granted to which users.
Example Queries:
-- Check what roles are granted to a specific user
SELECT * FROM DBA_ROLE_PRIVS WHERE GRANTEE = 'HR_SCHEMA';
-- Check direct system privileges for a user
SELECT * FROM DBA_SYS_PRIVS WHERE GRANTEE = 'HR_SCHEMA';
-- Check object privileges (table-level)
SELECT * FROM DBA_TAB_PRIVS WHERE GRANTEE = 'HR_SCHEMA';
-- List all database users and their default tablespace
SELECT USERNAME, DEFAULT_TABLESPACE, ACCOUNT_STATUS FROM
DBA_USERS;
2. Monitoring Audit Logs
Oracle auditing records who did what and when. These records are available via data
dictionary views once auditing is enabled.
Key Views for Auditing:
• DBA_AUDIT_TRAIL – Shows general audit records (user actions, timestamp,
privileges used).
• DBA_AUDIT_SESSION – Shows user login/logoff activities.
• DBA_AUDIT_OBJECT – Shows actions on specific database objects (e.g., table
updates).
• DBA_AUDIT_STATEMENT – Shows DDL or other SQL statement executions.
• DBA_FGA_AUDIT_TRAIL – Shows fine-grained auditing results if FGA is configured.
Example Queries:
-- Show all audit logs (general)
SELECT USERNAME, ACTION_NAME, OBJ_NAME, TIMESTAMP
FROM DBA_AUDIT_TRAIL
ORDER BY TIMESTAMP DESC;
-- Show user login/logoff activity
SELECT USERNAME, LOGON_TIME, LOGOFF_TIME
FROM DBA_AUDIT_SESSION
ORDER BY LOGON_TIME DESC;
-- Show audited actions on tables
SELECT USERNAME, ACTION_NAME, OBJ_NAME, TIMESTAMP
FROM DBA_AUDIT_OBJECT
WHERE OBJ_NAME = 'EMPLOYEES';
3. Practical DBA Workflow
Check who has powerful privileges:
SELECT * FROM DBA_SYS_PRIVS WHERE PRIVILEGE LIKE '%DBA%';
Verify unauthorized object access:
SELECT * FROM DBA_TAB_PRIVS WHERE OWNER='HR_SCHEMA' AND
GRANTEE!='HR_SCHEMA';
Audit who altered sensitive tables:
SELECT USERNAME, ACTION_NAME, OBJ_NAME, TIMESTAMP
FROM DBA_AUDIT_OBJECT
WHERE OBJ_NAME='SALARY' AND ACTION_NAME='UPDATE';
Monitor failed logins (security):
SELECT USERNAME, RETURNCODE, TIMESTAMP
FROM DBA_AUDIT_SESSION
WHERE RETURNCODE != 0;
24. Discuss the importance of role-based access control and how it's implemented in SQL.
Answer:
Role-Based Access Control Definition
Role-based access control (RBAC) is a method of protecting sensitive data from improper
access, modification, addition, or deletion. It allows employees to have access to the
information required to fulfill their responsibilities. Access rights and permissions are given to
employees based on their job roles and designations. This helps protect business-critical data
against misuse.
Basics of role-based access control
Three common principles of role-based access control include:
1. User role assignment: The permission or access rights are granted only if the individual
is assigned a role or a task.
2. User role authorization: The active role of the user in the task must be authorized.
3. User role permission and access rights: The individual can utilize their permission
rights only if they’re given the authorization to perform their active role.
Effective RBAC can help with granting systematic permissions and access to business-critical
information to improve cybersecurity and with maintaining compliance with regulations such
as HIPAA, GDPR, and more. Using an automated RBAC software solution can also provide
structured templates to monitor user access levels and simplify the audit process.
How does RBAC work?
An access rights system leveraging RBAC works on the principle of least privilege to help
ensure sensitive data security. Using RBAC can be extremely helpful for larger enterprises
with a great number of employees where administrators are facing difficulty in assigning
unique user credentials to each employee. With automated role-based access control,
administrators can create user groups with similar permissions and rights, assign roles and
responsibilities, and allow access to a defined set of resources.
Benefits of RBAC
Limiting unnecessary employee access to business-critical information can help ensure
security and compliance by:
o Improving operational efficiency: Role-based access control can help reduce manual
tasks and paperwork by streamlining the automation of access rights. With an RBAC
software solution, enterprises can more easily assign, modify, add, and delete roles and
responsibilities to enhance operational efficiency.
o Demonstrating compliance: Implementing RBAC will help organizations demonstrate
compliance with local, federal, and state regulations. This enables IT teams and
administrators to manage access to confidential data more effectively. Financial and
healthcare institutions can use RBAC to manage access to critical data, such as PCI and
PHI.
Best practices for implementing RBAC
By following a few best practices, implementing role-based access control can be a simple
process. Some best practices to help support RBAC include:
o Note the current user permissions assigned to resources. It’s important to have detailed
information and be able to easily view user access to applications and resources, such as
software and hardware.
o Use role-specific templates to assign access rights to only users who need them based
on job responsibilities and standardize user credentials.
o Track any modifications or changes made in user roles, access rights, and
permissions to identify and investigate privilege abuses, suspicious account activity, and
other vulnerabilities.
Role-based access control in Azure AD
Azure Active Directory provides two types of role-based access controls:
1. Built-in roles: Azure AD supports many built-in roles. However, each role includes a
fixed set of permissions that cannot be modified.
2. Custom roles: Azure AD also supports custom roles, including a collection of
permissions that can be modified depending on the role. Granting permissions using
custom roles is a two-step process. It involves creating a custom Azure AD role and
assigning the permissions from a preset list. A custom role can be assigned at an
organization level or object scope level. The member with custom permission rights can
have access to all the organization’s resources, while object-scope permissions are limited
to a single application.
RBAC vs. ABAC
Role-based access control and attribute-based access control (ABAC) are two different
methods of access control. The major difference between the two is RBAC grants access
based on the user roles and responsibilities while ABAC provides access based on
environmental attributes, resource attributes, user attributes, and other attributes.
25. What is Curser? Explain indetail and its types.
Answer:
In Oracle PL/SQL, a cursor is a pointer or handle used to fetch and process rows returned by a
SQL query, one at a time. Because SQL statements can return multiple rows but PL/SQL
variables can hold only one value at a time, cursors act as a bridge between multi-row query
results and PL/SQL’s row-by-row processing.
Why Use Cursors?
To process query results row by row.
To perform complex business logic on each row.
To improve clarity and control compared to implicit fetching.
Types of Cursors in PL/SQL
Implicit Cursor
Automatically created by Oracle when you execute a single SQL statement (e.g., INSERT,
UPDATE, DELETE, SELECT INTO) inside PL/SQL.
Oracle manages the opening, fetching, and closing.
The status of the last implicit cursor can be checked using the SQL Cursor Attributes:
SQL%FOUND – TRUE if rows were affected.
SQL%NOTFOUND – TRUE if no rows were affected.
SQL%ROWCOUNT – Number of rows affected.
SQL%ISOPEN – Always FALSE for implicit cursors (they close automatically).
Example:
BEGIN
UPDATE employees SET salary = salary * 1.1 WHERE dept_id = 10;
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows updated.');
ELSE
DBMS_OUTPUT.PUT_LINE('No rows updated.');
END IF;
END;
Explicit Cursor
Declared and managed manually by the programmer.
Useful when:
The query returns multiple rows.
You need step-by-step control over fetching and processing.
Steps to Use Explicit Cursor
Declare the cursor.
Open the cursor.
Fetch rows into variables.
Close the cursor.
Example:
DECLARE
CURSOR emp_cursor IS
SELECT emp_id, emp_name, salary FROM employees WHERE dept_id = 20;
v_id employees.emp_id%TYPE;
v_name employees.emp_name%TYPE;
v_salary employees.salary%TYPE;
BEGIN
OPEN emp_cursor; -- Step 2: Open
LOOP
FETCH emp_cursor INTO v_id, v_name, v_salary; -- Step 3: Fetch
EXIT WHEN emp_cursor%NOTFOUND; -- Exit when no more rows
DBMS_OUTPUT.PUT_LINE(v_id || ' - ' || v_name || ' - ' || v_salary);
END LOOP;
CLOSE emp_cursor; -- Step 4: Close
END;
Cursor FOR Loop
Simplifies explicit cursor handling by automatically opening, fetching, and closing the cursor.
Requires fewer lines of code.
Example:
BEGIN
FOR emp_rec IN (SELECT emp_id, emp_name, salary FROM employees WHERE dept_id
= 20) LOOP
DBMS_OUTPUT.PUT_LINE(emp_rec.emp_id || ' - ' || emp_rec.emp_name || ' - ' ||
emp_rec.salary);
END LOOP;
END;
Parameterized Cursor
Accepts parameters at runtime, making cursors more flexible.
Example:
DECLARE
CURSOR emp_cursor(p_dept_id NUMBER) IS
SELECT emp_id, emp_name FROM employees WHERE dept_id = p_dept_id;
BEGIN
FOR emp_rec IN emp_cursor(30) LOOP
DBMS_OUTPUT.PUT_LINE(emp_rec.emp_id || ' - ' || emp_rec.emp_name);
END LOOP;
END;
Cursor Attributes
Attribute Description
%FOUND TRUE if the last fetch returned a row.
%NOTFOUND TRUE if the last fetch did NOT return a row.
%ROWCOUNT Number of rows fetched so far.
Attribute Description
%ISOPEN TRUE if the cursor is open.