SlideShare a Scribd company logo
P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h
Visit: http://gsbprogramming.blogspot.in
P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h
Visit: http://gsbprogramming.blogspot.in
Assigning SQL Query Results to PL/SQL Variables
You cannot write SQL select statements directly in your PL/SQL block. For example:
BEGIN
SELECT emp_name, emp_salary FROM employee WHERE emp_id=10;
END;
When you run this code this will throw an error.
So to get the result of SQL select statements you have to use INTO clause.
Note: INTO clause is applicable only for single row SELECT statements
So to get assign SQL query results to PL/SQL variables we can use like:
DECLARE
vName varchar2(50);
vSalary number;
BEGIN
SELECT emp_name, emp_salary INTO vName,vSalary
FROM employee WHERE emp_id=10;
dbms_output.put_line(‘Name: ‘||vName||’ and Salary: ‘||vSalary);
END;
This will assign the name of employee to variable vName and salary of employee to variable vSalary
whose employee id is 10. The output will be:
Name: Gurpreet Singh and Salary: 100000
P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h
Visit: http://gsbprogramming.blogspot.in
Now this INTO clause is applicable only for single rows, So if you need to access the multiple rows then?
Then you can use the CURSORS
CURSORS
Oracle creates a memory area, known as context area, for processing an SQL statement, which contains
all information needed for processing the statement, for example, number of rows processed, etc. A
cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds
the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as
the active set. There are two types of cursors:
 Implicit Cursors
 Explicit Cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there
is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the
information in it.
When you write DML statements (INSERT, UPDATE, DELETE) then implicit cursor gets associated with it.
For example, when we write an INSERT statement then cursor holds the data to be inserted and when we
write DELETE or UPDATE statement then cursor holds the data that will be affected by those statements.
There are various attributes of implicit cursors:
Attribute Description
SQL%FOUND It tells whether any row has been affected with the statement. If one or
more is affected then it returns TRUE otherwise FALSE. For example, for an
update statement, if any row has been affected then it will return TRUE.
SQL%NOTFOUND It is opposite of SQL%FOUND. It returns TRUE if no row has been affected
SQL%ROWCOUNT It tells how many rows have been affected
For example:
P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h
Visit: http://gsbprogramming.blogspot.in
BEGIN
UPDATE employee SET emp_salary=1000 WHERE dept_id=20;
IF SQL%FOUND THEN
dbms_output.put_line(‘Salary of ‘||SQL%ROWCOUNT||’ employees is updated’);
ELSE
dbms_output.put_line(‘Salary not updated of any employee’);
END IF;
END;
Output:
Salary of 4 employees is updated
Explicit Cursors
Explicit cursors are defined by programmer. Explicit cursors are used for those select statements which
return more than one rows.
Working with Explicit Cursors:
 Declare the cursor for initializing in the memory
 Opening the cursor for allocating memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory
For example:
DECLARE OPEN FETCH CLOSE
P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h
Visit: http://gsbprogramming.blogspot.in
DECALRE
CURSOR c1 IS
SELECT emp_id, emp_name FROM employee WHERE dept_id=10;
vId number;
vName varchar2(50);
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO vId, vName;
EXIT WHEN c1%NOTFOUND;
dbms_output.put_line(‘ID: ‘||vId||’ Name: ‘||vName);
END LOOP;
CLOSE c1;
END;
It will display the ID and Name of those employees whose dept_id is 10
We can skip the OPEN, FETCH and CLOSE by using the for loop
DECALRE
CURSOR c1 IS
SELECT emp_id, emp_name FROM employee WHERE dept_id=10;
BEGIN
OPEN c1;
FOR c11 IN c1 LOOP
dbms_output.put_line(‘ID: ‘||c11.emp_id||’ Name: ‘||c11.emp_name);
END LOOP;
END;
P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h
Visit: http://gsbprogramming.blogspot.in
When we use for loop we can access the columns using the loop variable like we have used:
c11.emp_id and c11.emp_name
PASSING VALUES TO CURSORS
We can also pass the values to cursors. For example: in above example we can pass the dept_id rather
than just hard coding it to dept _id=10
DECALRE
CURSOR c1( id number) IS
SELECT emp_id, emp_name FROM employee WHERE dept_id=10;
BEGIN
OPEN c1;
FOR c11 IN c1(10) LOOP --Passing dept_id=10
dbms_output.put_line(‘ID: ‘||c11.emp_id||’ Name: ‘||c11.emp_name);
END LOOP;
END;
DECALRE
CURSOR c1( id number) IS
SELECT emp_id, emp_name FROM employee WHERE dept_id=10;
BEGIN
OPEN c1;
FOR c11 IN c1(20) LOOP --Passing dept_id=20
dbms_output.put_line(‘ID: ‘||c11.emp_id||’ Name: ‘||c11.emp_name);
END LOOP;
END;
P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h
Visit: http://gsbprogramming.blogspot.in
Similarly, we can pass other values.
Program to print the sum of salaries of the employees whose salary is greater than 1000
DECALRE
CURSOR c1 IS
SELECT emp_salary FROM employee ORDER BY salary DESC;
vSum number :=0;
BEGIN
OPEN c1;
FOR c11 IN c1 LOOP
IF c11.salary<=1000 THEN
EXIT;
vSum:= vSum+c11.emp_salary;
END LOOP;
dbms_output.put_line(‘Total Sum: ‘||vSum);
END;

More Related Content

Viewers also liked

Sistemas operativos prof.julia
Sistemas operativos prof.juliaSistemas operativos prof.julia
Sistemas operativos prof.julia
aerma5
 
Fluzz pilulas 9
Fluzz pilulas 9Fluzz pilulas 9
Fluzz pilulas 9
augustodefranco .
 
Emprender
EmprenderEmprender
Emprender
betete
 
La niñez
La niñezLa niñez
TEFFICK RAGBEER Resume 01
TEFFICK RAGBEER Resume 01TEFFICK RAGBEER Resume 01
TEFFICK RAGBEER Resume 01
Teffick Ragbeer
 
Analise de conteudo
Analise de conteudoAnalise de conteudo
Analise de conteudo
Lucila Pesce
 
Caminho MaríTimo Para O Brasil
Caminho MaríTimo Para O BrasilCaminho MaríTimo Para O Brasil
Caminho MaríTimo Para O Brasil
crie_historia8
 
Hallow'een 2012 | Teacher Isabel Ferreira
Hallow'een 2012 | Teacher Isabel FerreiraHallow'een 2012 | Teacher Isabel Ferreira
Hallow'een 2012 | Teacher Isabel Ferreira
AEC-Inglês
 
Easter Egg Hunt - E.B. da Estalagem
Easter Egg Hunt - E.B. da EstalagemEaster Egg Hunt - E.B. da Estalagem
Easter Egg Hunt - E.B. da Estalagem
AEC-Inglês
 
Slide historia
Slide historiaSlide historia
Slide historia
Celiamariag3
 

Viewers also liked (10)

Sistemas operativos prof.julia
Sistemas operativos prof.juliaSistemas operativos prof.julia
Sistemas operativos prof.julia
 
Fluzz pilulas 9
Fluzz pilulas 9Fluzz pilulas 9
Fluzz pilulas 9
 
Emprender
EmprenderEmprender
Emprender
 
La niñez
La niñezLa niñez
La niñez
 
TEFFICK RAGBEER Resume 01
TEFFICK RAGBEER Resume 01TEFFICK RAGBEER Resume 01
TEFFICK RAGBEER Resume 01
 
Analise de conteudo
Analise de conteudoAnalise de conteudo
Analise de conteudo
 
Caminho MaríTimo Para O Brasil
Caminho MaríTimo Para O BrasilCaminho MaríTimo Para O Brasil
Caminho MaríTimo Para O Brasil
 
Hallow'een 2012 | Teacher Isabel Ferreira
Hallow'een 2012 | Teacher Isabel FerreiraHallow'een 2012 | Teacher Isabel Ferreira
Hallow'een 2012 | Teacher Isabel Ferreira
 
Easter Egg Hunt - E.B. da Estalagem
Easter Egg Hunt - E.B. da EstalagemEaster Egg Hunt - E.B. da Estalagem
Easter Egg Hunt - E.B. da Estalagem
 
Slide historia
Slide historiaSlide historia
Slide historia
 

More from Gurpreet singh

Creating ESS Jobs for Oracle Fusion BIP Reports
Creating ESS Jobs for Oracle Fusion BIP ReportsCreating ESS Jobs for Oracle Fusion BIP Reports
Creating ESS Jobs for Oracle Fusion BIP Reports
Gurpreet singh
 
Introduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP ReportingIntroduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP Reporting
Gurpreet singh
 
Why Messaging system?
Why Messaging system?Why Messaging system?
Why Messaging system?
Gurpreet singh
 
Understanding Flex Fields with Accounting Flexfields(Chart of Accounts) in O...
Understanding Flex Fields with  Accounting Flexfields(Chart of Accounts) in O...Understanding Flex Fields with  Accounting Flexfields(Chart of Accounts) in O...
Understanding Flex Fields with Accounting Flexfields(Chart of Accounts) in O...
Gurpreet singh
 
Oracle Application Developmenr Framework
Oracle Application Developmenr FrameworkOracle Application Developmenr Framework
Oracle Application Developmenr Framework
Gurpreet singh
 
Java Servlet part 3
Java Servlet part 3Java Servlet part 3
Java Servlet part 3
Gurpreet singh
 
Oracle advanced queuing
Oracle advanced queuingOracle advanced queuing
Oracle advanced queuing
Gurpreet singh
 
Oracle SQL Part 3
Oracle SQL Part 3Oracle SQL Part 3
Oracle SQL Part 3
Gurpreet singh
 
Oracle SQL Part 2
Oracle SQL Part 2Oracle SQL Part 2
Oracle SQL Part 2
Gurpreet singh
 
Oracle SQL Part1
Oracle SQL Part1Oracle SQL Part1
Oracle SQL Part1
Gurpreet singh
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
Gurpreet singh
 
Java Servlets Part 2
Java Servlets Part 2Java Servlets Part 2
Java Servlets Part 2
Gurpreet singh
 
Creating business group in oracle apps
Creating business group in oracle appsCreating business group in oracle apps
Creating business group in oracle apps
Gurpreet singh
 
Defing locations in Oracle Apps
Defing locations in Oracle AppsDefing locations in Oracle Apps
Defing locations in Oracle Apps
Gurpreet singh
 
Assigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYSTAssigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYST
Gurpreet singh
 
PL/SQL Part 5
PL/SQL Part 5PL/SQL Part 5
PL/SQL Part 5
Gurpreet singh
 
PL/SQL Part 3
PL/SQL Part 3PL/SQL Part 3
PL/SQL Part 3
Gurpreet singh
 
PL/SQL Part 2
PL/SQL Part 2PL/SQL Part 2
PL/SQL Part 2
Gurpreet singh
 
Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)
Gurpreet singh
 

More from Gurpreet singh (20)

Creating ESS Jobs for Oracle Fusion BIP Reports
Creating ESS Jobs for Oracle Fusion BIP ReportsCreating ESS Jobs for Oracle Fusion BIP Reports
Creating ESS Jobs for Oracle Fusion BIP Reports
 
Introduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP ReportingIntroduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP Reporting
 
Why Messaging system?
Why Messaging system?Why Messaging system?
Why Messaging system?
 
Understanding Flex Fields with Accounting Flexfields(Chart of Accounts) in O...
Understanding Flex Fields with  Accounting Flexfields(Chart of Accounts) in O...Understanding Flex Fields with  Accounting Flexfields(Chart of Accounts) in O...
Understanding Flex Fields with Accounting Flexfields(Chart of Accounts) in O...
 
Oracle Application Developmenr Framework
Oracle Application Developmenr FrameworkOracle Application Developmenr Framework
Oracle Application Developmenr Framework
 
Java Servlet part 3
Java Servlet part 3Java Servlet part 3
Java Servlet part 3
 
Oracle advanced queuing
Oracle advanced queuingOracle advanced queuing
Oracle advanced queuing
 
Oracle SQL Part 3
Oracle SQL Part 3Oracle SQL Part 3
Oracle SQL Part 3
 
Oracle SQL Part 2
Oracle SQL Part 2Oracle SQL Part 2
Oracle SQL Part 2
 
Oracle SQL Part1
Oracle SQL Part1Oracle SQL Part1
Oracle SQL Part1
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
 
Java Servlets Part 2
Java Servlets Part 2Java Servlets Part 2
Java Servlets Part 2
 
Creating business group in oracle apps
Creating business group in oracle appsCreating business group in oracle apps
Creating business group in oracle apps
 
Defing locations in Oracle Apps
Defing locations in Oracle AppsDefing locations in Oracle Apps
Defing locations in Oracle Apps
 
Assigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYSTAssigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYST
 
PL/SQL Part 5
PL/SQL Part 5PL/SQL Part 5
PL/SQL Part 5
 
PL/SQL Part 3
PL/SQL Part 3PL/SQL Part 3
PL/SQL Part 3
 
PL/SQL Part 2
PL/SQL Part 2PL/SQL Part 2
PL/SQL Part 2
 
Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)
 

Recently uploaded

GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 

Recently uploaded (20)

GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 

PL/SQL Part 6

  • 1. P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h Visit: http://gsbprogramming.blogspot.in
  • 2. P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h Visit: http://gsbprogramming.blogspot.in Assigning SQL Query Results to PL/SQL Variables You cannot write SQL select statements directly in your PL/SQL block. For example: BEGIN SELECT emp_name, emp_salary FROM employee WHERE emp_id=10; END; When you run this code this will throw an error. So to get the result of SQL select statements you have to use INTO clause. Note: INTO clause is applicable only for single row SELECT statements So to get assign SQL query results to PL/SQL variables we can use like: DECLARE vName varchar2(50); vSalary number; BEGIN SELECT emp_name, emp_salary INTO vName,vSalary FROM employee WHERE emp_id=10; dbms_output.put_line(‘Name: ‘||vName||’ and Salary: ‘||vSalary); END; This will assign the name of employee to variable vName and salary of employee to variable vSalary whose employee id is 10. The output will be: Name: Gurpreet Singh and Salary: 100000
  • 3. P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h Visit: http://gsbprogramming.blogspot.in Now this INTO clause is applicable only for single rows, So if you need to access the multiple rows then? Then you can use the CURSORS CURSORS Oracle creates a memory area, known as context area, for processing an SQL statement, which contains all information needed for processing the statement, for example, number of rows processed, etc. A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set. There are two types of cursors:  Implicit Cursors  Explicit Cursors Implicit Cursors Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it. When you write DML statements (INSERT, UPDATE, DELETE) then implicit cursor gets associated with it. For example, when we write an INSERT statement then cursor holds the data to be inserted and when we write DELETE or UPDATE statement then cursor holds the data that will be affected by those statements. There are various attributes of implicit cursors: Attribute Description SQL%FOUND It tells whether any row has been affected with the statement. If one or more is affected then it returns TRUE otherwise FALSE. For example, for an update statement, if any row has been affected then it will return TRUE. SQL%NOTFOUND It is opposite of SQL%FOUND. It returns TRUE if no row has been affected SQL%ROWCOUNT It tells how many rows have been affected For example:
  • 4. P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h Visit: http://gsbprogramming.blogspot.in BEGIN UPDATE employee SET emp_salary=1000 WHERE dept_id=20; IF SQL%FOUND THEN dbms_output.put_line(‘Salary of ‘||SQL%ROWCOUNT||’ employees is updated’); ELSE dbms_output.put_line(‘Salary not updated of any employee’); END IF; END; Output: Salary of 4 employees is updated Explicit Cursors Explicit cursors are defined by programmer. Explicit cursors are used for those select statements which return more than one rows. Working with Explicit Cursors:  Declare the cursor for initializing in the memory  Opening the cursor for allocating memory  Fetching the cursor for retrieving the data  Closing the cursor to release the allocated memory For example: DECLARE OPEN FETCH CLOSE
  • 5. P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h Visit: http://gsbprogramming.blogspot.in DECALRE CURSOR c1 IS SELECT emp_id, emp_name FROM employee WHERE dept_id=10; vId number; vName varchar2(50); BEGIN OPEN c1; LOOP FETCH c1 INTO vId, vName; EXIT WHEN c1%NOTFOUND; dbms_output.put_line(‘ID: ‘||vId||’ Name: ‘||vName); END LOOP; CLOSE c1; END; It will display the ID and Name of those employees whose dept_id is 10 We can skip the OPEN, FETCH and CLOSE by using the for loop DECALRE CURSOR c1 IS SELECT emp_id, emp_name FROM employee WHERE dept_id=10; BEGIN OPEN c1; FOR c11 IN c1 LOOP dbms_output.put_line(‘ID: ‘||c11.emp_id||’ Name: ‘||c11.emp_name); END LOOP; END;
  • 6. P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h Visit: http://gsbprogramming.blogspot.in When we use for loop we can access the columns using the loop variable like we have used: c11.emp_id and c11.emp_name PASSING VALUES TO CURSORS We can also pass the values to cursors. For example: in above example we can pass the dept_id rather than just hard coding it to dept _id=10 DECALRE CURSOR c1( id number) IS SELECT emp_id, emp_name FROM employee WHERE dept_id=10; BEGIN OPEN c1; FOR c11 IN c1(10) LOOP --Passing dept_id=10 dbms_output.put_line(‘ID: ‘||c11.emp_id||’ Name: ‘||c11.emp_name); END LOOP; END; DECALRE CURSOR c1( id number) IS SELECT emp_id, emp_name FROM employee WHERE dept_id=10; BEGIN OPEN c1; FOR c11 IN c1(20) LOOP --Passing dept_id=20 dbms_output.put_line(‘ID: ‘||c11.emp_id||’ Name: ‘||c11.emp_name); END LOOP; END;
  • 7. P L / S Q L T u t o r i a l - B y E r G u r p r e e t S i n g h Visit: http://gsbprogramming.blogspot.in Similarly, we can pass other values. Program to print the sum of salaries of the employees whose salary is greater than 1000 DECALRE CURSOR c1 IS SELECT emp_salary FROM employee ORDER BY salary DESC; vSum number :=0; BEGIN OPEN c1; FOR c11 IN c1 LOOP IF c11.salary<=1000 THEN EXIT; vSum:= vSum+c11.emp_salary; END LOOP; dbms_output.put_line(‘Total Sum: ‘||vSum); END;