The document discusses stored procedures and embedded SQL. Stored procedures allow functions to be stored on the database server and reduce network traffic by being invoked multiple times. They can be written in languages like SQL, C, or Java. Embedded SQL is used to interface SQL with a host programming language by embedding SQL statements directly into program code using syntax like EXEC SQL.
The document discusses PL/SQL programming concepts like procedures, cursors, and how to build and use them. It provides examples of creating procedures that update employee salaries, using cursors to loop through database records, and controlling cursor flow. The seminar exercise asks students to create a procedure that increases employee salaries by £500 or £1000 depending on the employee's grade level using concepts covered in the document.
A stored procedure is a subroutine available to applications that access a relational database. Extensive or complex SQL processing is moved into stored procedures to improve performance. Stored procedures offer advantages like improved security, reduced network traffic, and easier maintenance compared to embedding SQL statements in an application. They allow parameters to be passed in and support flow control structures like IF/THEN clauses.
A stored procedure is a subroutine stored in a database that can be called to perform a specific task. Stored procedures consolidate and centralize logic that was originally implemented across multiple applications. They improve performance by only sending the procedure name and parameters rather than multiple SQL statements. Stored procedures also increase security by allowing access permissions to be set at the procedure level. Common uses include data validation and access control mechanisms integrated into the database.
The document discusses functions and stored procedures in SQL. Functions are logical grouped SQL/PL statements that perform a specific task and return a value, while stored procedures perform a specific task without returning a value. The document provides examples of creating simple SQL functions that return values and a stored procedure that updates employee salaries and bonuses.
The document discusses functions and stored procedures in SQL. Functions are logical grouped SQL/PL statements that perform a specific task and return a value, while stored procedures perform a specific task without returning a value. The document provides examples of creating simple SQL functions that return values and a stored procedure that updates employee salaries and bonuses.
The document provides information about stored procedures in databases:
- A stored procedure is a way to encapsulate repetitive tasks like queries into reusable code blocks stored in the database.
- Stored procedures offer advantages like precompiled execution for improved performance, reduced network traffic, code reuse, and enhanced security.
- The example shows how to create a stored procedure using delimiters to change parsing behavior and pass parameters to a procedure. Cursors allow fetching multiple rows from a result set into variables.
This document discusses stored procedures in MySQL. Key points:
- Stored procedures are subroutines stored in a database that can take parameters and return values. They are written in MySQL and stored on the server.
- Benefits include reducing duplication, improving security, and reducing network traffic compared to sending multiple SQL statements.
- Disadvantages include difficulty debugging and increased memory usage with many procedures.
- Procedures can take IN, OUT, and INOUT parameters to pass values between the calling code and procedure. Variables and conditionals like IF statements can also be used inside procedures.
This document discusses stored procedures in MySQL and MSSQL, including their advantages, syntax, and examples. It also covers the differences between procedures and functions, and provides an example of creating a trigger to update total department salaries when employees are inserted, updated, or deleted.
PL/SQL provides two types of composite datatypes - records and collections. Records allow grouping of related data elements, while collections allow storing multiple values in a single variable. Collections include index-by tables, nested tables, and varrays. Cursors allow processing rows from a SQL query one by one. Explicit cursors must be declared, opened, fetched from, and closed. Implicit cursors are used for DML statements. Functions return a value and can be used in SQL expressions, while procedures perform actions without returning a value. Both can accept parameters.
Stored procedures are blocks of SQL code that can be stored on a database server for repeated execution. They allow for encapsulation of repetitive tasks, improved security, and better performance compared to executing SQL statements directly from a client application. Key features of stored procedures include portability, reusability, and the ability to accept parameters and return values. Common SQL statements like SELECT, INSERT, UPDATE and DELETE can be used within a stored procedure. Functions are similar but can only return a single value and have additional limitations compared to procedures.
The document discusses cursors in Oracle databases. It defines cursors as temporary work areas for processing query results row by row. There are two main types of cursors - implicit and explicit. Explicit cursors provide more control and involve declaring, opening, fetching from, and closing the cursor. Examples demonstrate using explicit cursors to retrieve and process multiple rows in a PL/SQL block. The document also covers cursor attributes, cursor for loops, parameterized cursors, and comparisons of implicit and explicit cursors.
This document discusses stored procedures in databases. It provides an overview of stored procedures, their advantages like reduced network traffic, and how they allow local variables, loops, and examination of data tuples. It describes how to write stored procedures using languages like SQL, including declaring parameters, and provides examples of stored procedures using conditional statements, loops, and cursors to process data.
The document discusses several SQL concepts:
[1] Subqueries, which can be noncorrelated (independent of the outer query) or correlated (contains references to the outer query). Correlated subqueries cannot be run independently.
[2] Views, which provide security, simplify queries, and insulate from changes, but can reduce performance and manageability. Views restrict access and update capabilities.
[3] Stored procedures, which increase performance but require specialized skills. Stored procedures accept parameters, contain multiple statements, and perform modifications, while views are limited to single SELECTs.
This document provides an overview of SQL (Structured Query Language) in 3 sentences or less:
SQL is a standard language for storing, manipulating and retrieving data in relational database systems. The document outlines various SQL commands, clauses, and functions for working with data types, tables, queries, procedures, indexes and more. Examples are provided to illustrate how to use SQL statements to define schemas, insert, update, select and manipulate data in relational database tables.
This document discusses stored procedures in databases. It defines a stored procedure as a program code stored in the database server that encapsulates repetitive tasks. Stored procedures can make tasks faster by pre-compiling the code rather than compiling it each time. The document provides the syntax for creating, calling, and deleting stored procedures. It also discusses parameters, cursors, and declare handlers. Examples are given to illustrate stored procedures.
What is PL/SQL
Procedural Language – SQL
An extension to SQL with design features of programming languages (procedural and object oriented)
PL/SQL and Java are both supported as internal host languages within Oracle products.
This document provides an overview of stored procedures in MySQL, including what they are, why they are used, how they work, and examples of different types of stored procedures. Key points covered include:
- Stored procedures are subroutines that consolidate and centralize database logic. They can improve performance by reducing network traffic and allowing code reuse.
- Examples demonstrate basic stored procedures without parameters, as well as those using parameters, IF/THEN statements, CASE statements, LOOPs, and CURSORs to iterate through result sets.
- Limitations include increased memory usage, difficulty debugging, and specialized skill requirements for development and maintenance.
This document provides an overview and introduction to advanced PL/SQL concepts. It covers fundamentals like data types, control structures, cursors, exceptions and error handling. It also discusses more advanced topics such as Oracle types and collections, interacting with Oracle databases using PL/SQL, creating subprograms and packages, and error handling. The document is presented by Vinay Kumar and intended to teach advanced PL/SQL concepts.
The document discusses different procedural SQL concepts like cursors, user defined functions, and stored procedures. It provides examples of creating functions that return values and tables, as well as procedures that update data. The examples demonstrate how to define parameters, return values, and write PL/SQL code within functions and procedures to perform tasks like updating records and returning results.
Views allow querying of data from other tables without storing a separate physical table. Stored procedures allow reusable sequences of SQL statements to be stored in database. Functions return a value and can be used in queries. Triggers allow automated actions such as updates in response to data changes.
This document discusses stored procedures in SQL Server. It begins by explaining that stored procedures allow encapsulation of repetitive tasks and are stored in the database data dictionary. It then shows how stored procedures reduce network traffic and client-server communication compared to individual SQL statements. The document provides examples of how to create a stored procedure using CREATE PROCEDURE and how to call it using EXEC. It notes advantages like precompiled execution, reduced traffic, code reuse, and security control. It also demonstrates using parameters, loops, conditions and variables inside stored procedures.
This document discusses explicit cursors in PL/SQL. It defines implicit and explicit cursors, with implicit cursors being used for all DML statements and single-row queries, while explicit cursors are used for queries that return zero, one, or more rows. The document outlines how to declare, open, fetch from, and close an explicit cursor. It also covers using cursors with parameters, locking rows with FOR UPDATE, and updating the current row with WHERE CURRENT OF.
A cursor allows you to iterate over the rows returned by a SQL query one row at a time. There are two types of cursors: implicit, which are automatically declared, and explicit, which must be declared by the programmer. Cursors in MySQL are read-only, non-scrollable, and sensitive to changes in the underlying table. The basic cursor syntax includes commands to declare, open, fetch from, and close a cursor. An example stored procedure demonstrates how to build a list of names from a database table using a cursor.
Cursors in SQL procedures allow defining a result set that can be iterated through row by row. A cursor acts as a pointer to each row in turn. To use a cursor, it must be declared to define the result set, opened to establish the set, individual rows can then be fetched and processed one at a time using variables, and the cursor is closed once complete. Basic cursor usage involves the DECLARE, OPEN, FETCH and CLOSE statements. An example demonstrates summing the salaries from an employee table by declaring a cursor over it, fetching rows into a variable and accumulating the sum in a loop.
Test your knowledge of the Python programming language with this quiz! Covering topics such as:
- Syntax and basics
- Data structures (lists, tuples, dictionaries, etc.)
- Control structures (if-else, loops, etc.)
- Functions and modules
- Object-Oriented Programming (OOP) concepts
Challenge yourself and see how well you can score!
This document discusses stored procedures in MySQL. Key points:
- Stored procedures are subroutines stored in a database that can take parameters and return values. They are written in MySQL and stored on the server.
- Benefits include reducing duplication, improving security, and reducing network traffic compared to sending multiple SQL statements.
- Disadvantages include difficulty debugging and increased memory usage with many procedures.
- Procedures can take IN, OUT, and INOUT parameters to pass values between the calling code and procedure. Variables and conditionals like IF statements can also be used inside procedures.
This document discusses stored procedures in MySQL and MSSQL, including their advantages, syntax, and examples. It also covers the differences between procedures and functions, and provides an example of creating a trigger to update total department salaries when employees are inserted, updated, or deleted.
PL/SQL provides two types of composite datatypes - records and collections. Records allow grouping of related data elements, while collections allow storing multiple values in a single variable. Collections include index-by tables, nested tables, and varrays. Cursors allow processing rows from a SQL query one by one. Explicit cursors must be declared, opened, fetched from, and closed. Implicit cursors are used for DML statements. Functions return a value and can be used in SQL expressions, while procedures perform actions without returning a value. Both can accept parameters.
Stored procedures are blocks of SQL code that can be stored on a database server for repeated execution. They allow for encapsulation of repetitive tasks, improved security, and better performance compared to executing SQL statements directly from a client application. Key features of stored procedures include portability, reusability, and the ability to accept parameters and return values. Common SQL statements like SELECT, INSERT, UPDATE and DELETE can be used within a stored procedure. Functions are similar but can only return a single value and have additional limitations compared to procedures.
The document discusses cursors in Oracle databases. It defines cursors as temporary work areas for processing query results row by row. There are two main types of cursors - implicit and explicit. Explicit cursors provide more control and involve declaring, opening, fetching from, and closing the cursor. Examples demonstrate using explicit cursors to retrieve and process multiple rows in a PL/SQL block. The document also covers cursor attributes, cursor for loops, parameterized cursors, and comparisons of implicit and explicit cursors.
This document discusses stored procedures in databases. It provides an overview of stored procedures, their advantages like reduced network traffic, and how they allow local variables, loops, and examination of data tuples. It describes how to write stored procedures using languages like SQL, including declaring parameters, and provides examples of stored procedures using conditional statements, loops, and cursors to process data.
The document discusses several SQL concepts:
[1] Subqueries, which can be noncorrelated (independent of the outer query) or correlated (contains references to the outer query). Correlated subqueries cannot be run independently.
[2] Views, which provide security, simplify queries, and insulate from changes, but can reduce performance and manageability. Views restrict access and update capabilities.
[3] Stored procedures, which increase performance but require specialized skills. Stored procedures accept parameters, contain multiple statements, and perform modifications, while views are limited to single SELECTs.
This document provides an overview of SQL (Structured Query Language) in 3 sentences or less:
SQL is a standard language for storing, manipulating and retrieving data in relational database systems. The document outlines various SQL commands, clauses, and functions for working with data types, tables, queries, procedures, indexes and more. Examples are provided to illustrate how to use SQL statements to define schemas, insert, update, select and manipulate data in relational database tables.
This document discusses stored procedures in databases. It defines a stored procedure as a program code stored in the database server that encapsulates repetitive tasks. Stored procedures can make tasks faster by pre-compiling the code rather than compiling it each time. The document provides the syntax for creating, calling, and deleting stored procedures. It also discusses parameters, cursors, and declare handlers. Examples are given to illustrate stored procedures.
What is PL/SQL
Procedural Language – SQL
An extension to SQL with design features of programming languages (procedural and object oriented)
PL/SQL and Java are both supported as internal host languages within Oracle products.
This document provides an overview of stored procedures in MySQL, including what they are, why they are used, how they work, and examples of different types of stored procedures. Key points covered include:
- Stored procedures are subroutines that consolidate and centralize database logic. They can improve performance by reducing network traffic and allowing code reuse.
- Examples demonstrate basic stored procedures without parameters, as well as those using parameters, IF/THEN statements, CASE statements, LOOPs, and CURSORs to iterate through result sets.
- Limitations include increased memory usage, difficulty debugging, and specialized skill requirements for development and maintenance.
This document provides an overview and introduction to advanced PL/SQL concepts. It covers fundamentals like data types, control structures, cursors, exceptions and error handling. It also discusses more advanced topics such as Oracle types and collections, interacting with Oracle databases using PL/SQL, creating subprograms and packages, and error handling. The document is presented by Vinay Kumar and intended to teach advanced PL/SQL concepts.
The document discusses different procedural SQL concepts like cursors, user defined functions, and stored procedures. It provides examples of creating functions that return values and tables, as well as procedures that update data. The examples demonstrate how to define parameters, return values, and write PL/SQL code within functions and procedures to perform tasks like updating records and returning results.
Views allow querying of data from other tables without storing a separate physical table. Stored procedures allow reusable sequences of SQL statements to be stored in database. Functions return a value and can be used in queries. Triggers allow automated actions such as updates in response to data changes.
This document discusses stored procedures in SQL Server. It begins by explaining that stored procedures allow encapsulation of repetitive tasks and are stored in the database data dictionary. It then shows how stored procedures reduce network traffic and client-server communication compared to individual SQL statements. The document provides examples of how to create a stored procedure using CREATE PROCEDURE and how to call it using EXEC. It notes advantages like precompiled execution, reduced traffic, code reuse, and security control. It also demonstrates using parameters, loops, conditions and variables inside stored procedures.
This document discusses explicit cursors in PL/SQL. It defines implicit and explicit cursors, with implicit cursors being used for all DML statements and single-row queries, while explicit cursors are used for queries that return zero, one, or more rows. The document outlines how to declare, open, fetch from, and close an explicit cursor. It also covers using cursors with parameters, locking rows with FOR UPDATE, and updating the current row with WHERE CURRENT OF.
A cursor allows you to iterate over the rows returned by a SQL query one row at a time. There are two types of cursors: implicit, which are automatically declared, and explicit, which must be declared by the programmer. Cursors in MySQL are read-only, non-scrollable, and sensitive to changes in the underlying table. The basic cursor syntax includes commands to declare, open, fetch from, and close a cursor. An example stored procedure demonstrates how to build a list of names from a database table using a cursor.
Cursors in SQL procedures allow defining a result set that can be iterated through row by row. A cursor acts as a pointer to each row in turn. To use a cursor, it must be declared to define the result set, opened to establish the set, individual rows can then be fetched and processed one at a time using variables, and the cursor is closed once complete. Basic cursor usage involves the DECLARE, OPEN, FETCH and CLOSE statements. An example demonstrates summing the salaries from an employee table by declaring a cursor over it, fetching rows into a variable and accumulating the sum in a loop.
Test your knowledge of the Python programming language with this quiz! Covering topics such as:
- Syntax and basics
- Data structures (lists, tuples, dictionaries, etc.)
- Control structures (if-else, loops, etc.)
- Functions and modules
- Object-Oriented Programming (OOP) concepts
Challenge yourself and see how well you can score!
THE RISK ASSESSMENT AND TREATMENT APPROACH IN ORDER TO PROVIDE LAN SECURITY B...ijfcstjournal
Local Area Networks(LAN) at present become an important instrument for organizing of process and
information communication in an organization. They provides important purposes such as association of
large amount of data, hardware and software resources and expanding of optimum communications.
Becase these network do work with valuable information, the problem of security providing is an important
issue in organization. So, the stablishment of an information security management system(ISMS) in
organization is significant. In this paper, we introduce ISMS and its implementation in LAN scop. The
assets of LAN and threats and vulnerabilities of these assets are identified, the risks are evaluated and
techniques to reduce them and at result security establishment of the network is expressed.
Ceramic Multichannel Membrane Structure with Tunable Properties by Sol-Gel Me...DanyalNaseer3
A novel asymmetric ceramic membrane structure for different applications of wastewater treatment. With optimized layers- from macroporous support to nanofiltration-this innovative synthesis approach enhances permeability and antifouling properties of the membranes, offering a durable and high-performance alternative to conventional membranes in challenging environments.
As an AI intern at Edunet Foundation, I developed and worked on a predictive model for weather forecasting. The project involved designing and implementing machine learning algorithms to analyze meteorological data and generate accurate predictions. My role encompassed data preprocessing, model selection, and performance evaluation to ensure optimal forecasting accuracy.
Comprehensive Guide to Distribution Line DesignRadharaman48
The Comprehensive Guide to Distribution Line Design offers an in-depth overview of the key principles and best practices involved in designing electrical distribution lines. It covers essential aspects such as line routing, structural layout, pole placement, and coordination with terrain and infrastructure. The guide also explores the two main types of distribution systems Overhead and Underground distribution lines highlighting their construction methods, design considerations, and areas of application.
It provides a clear comparison between overhead and underground systems in terms of installation, maintenance, reliability, safety, and visual impact. Additionally, it discusses various types of cables used in distribution networks, including their classifications based on voltage levels, insulation, and usage in either overhead or underground settings.
Emphasizing safety, reliability, regulatory compliance, and environmental factors, this guide serves as a foundational resource for professionals and students looking to understand how distribution networks are designed to efficiently and securely deliver electricity from substations to consumers.
International Journal of Advance Robotics & Expert Systems (JARES)jaresjournal868
Advance Robotics & Expert Systems carry original articles, review articles, case studies and short communications from all over the world. The main aim of this journal is to extend the state of the art on theoretical, computational and experimental aspects of expert systems related to the applied fields such as transportation, surveillance, medical and industrial domains. This journal is also concentrated on kinematics, dynamics and syntheses of various robot locomotion mechanisms such as walk, jump, run, slide, skate, swim, fly, roll etc.
This project report explores the critical domain of cybersecurity, focusing on the practices and principles of ethical hacking as a proactive defense mechanism. With the rapid growth of digital technologies, organizations face a wide range of threats including data breaches, malware attacks, phishing scams, and ransomware. Ethical hacking, also known as penetration testing, involves simulating cyberattacks in a controlled and legal environment to identify system vulnerabilities before malicious hackers can exploit them.
Peak ground acceleration (PGA) is a critical parameter in ground-motion investigations, in particular in earthquake-prone areas such as Iran. In the current study, a new method based on particle swarm optimization (PSO) is developed to obtain an efficient attenuation relationship for the vertical PGA component within the northern Iranian plateau. The main purpose of this study is to propose suitable attenuation relationships for calculating the PGA for the Alborz, Tabriz and Kopet Dag faults in the vertical direction. To this aim, the available catalogs of the study area are investigated, and finally about 240 earthquake records (with a moment magnitude of 4.1 to 6.4) are chosen to develop the model. Afterward, the PSO algorithm is used to estimate model parameters, i.e., unknown coefficients of the model (attenuation relationship). Different statistical criteria showed the acceptable performance of the proposed relationships in the estimation of vertical PGA components in comparison to the previously developed relationships for the northern plateau of Iran. Developed attenuation relationships in the current study are independent of shear wave velocity. This issue is the advantage of proposed relationships for utilizing in the situations where there are not sufficient shear wave velocity data.
Liquefaction occurs when saturated, non-cohesive soil loses strength. This phenomenon occurs as the water pressure in the pores rises and the effective stress drops because of dynamic loading. Liquefaction potential is a ratio for the factor of safety used to figure out if the soil can be liquefied, and liquefaction-induced settlements happen when the ground loses its ability to support construction due to liquefaction. Traditionally, empirical and semi-empirical methods have been used to predict liquefaction potential and settlements that are based on historical data. In this study, MATLAB's Fuzzy Tool Adaptive Neuro-Fuzzy Inference System (ANFIS) (sub-clustering) was used to predict liquefaction potential and liquefaction-induced settlements. Using Cone Penetration Test (CPT) data, two ANFIS models were made: one to predict liquefaction potential (LP-ANFIS) and the other to predict liquefaction-induced settlements (LIS-ANFIS). The RMSE correlation for the LP-ANFIS model (input parameters: Depth, Cone penetration, Sleeve Resistance, and Effective stress; output parameters: Liquefaction Potential) and the LIS-ANFIS model (input parameters: Depth, Cone penetration, Sleeve Resistance, and Effective stress; output parameters: Settlements) was 0.0140764 and 0.00393882 respectively. The Coefficient of Determination (R2) for both the models was 0.9892 and 0.9997 respectively. Using the ANFIS 3D-Surface Diagrams were plotted to show the correlation between the CPT test parameters, the liquefaction potential, and the liquefaction-induced settlements. The ANFIS model results displayed that the considered soft computing techniques have good capabilities to determine liquefaction potential and liquefaction-induced settlements using CPT data.
Although the exploitation of GWO advances sharply, it has limitations for continuous implementing exploration. On the other hand, the EHO algorithm easily has shown its capability to prevent local optima. For hybridization and by considering the advantages of GWO and the abilities of EHO, it would be impressive to combine these two algorithms. In this respect, the exploitation and exploration performances and the convergence speed of the GWO algorithm are improved by combining it with the EHO algorithm. Therefore, this paper proposes a new hybrid Grey Wolf Optimizer (GWO) combined with Elephant Herding Optimization (EHO) algorithm. Twenty-three benchmark mathematical optimization challenges and six constrained engineering challenges are used to validate the performance of the suggested GWOEHO compared to both the original GWO and EHO algorithms and some other well-known optimization algorithms. Wilcoxon's rank-sum test outcomes revealed that GWOEHO outperforms others in most function minimization. The results also proved that the convergence speed of GWOEHO is faster than the original algorithms.
A passionate and result-oriented with over 28 years of multi-disciplinary experience in engineering, construction & maintenance management, and quality control works in oil and gas (offshore and onshore), industrial, and commercial projects. With proven ability in supervising design engineering (FEED) and managing construction, testing, commissioning, and handover of various scales of mechanical, electrical, plumbing, fire protection (MEPF), plant mechanical equipment (static/ rotating), piping, pipeline, and civil projects. A licensed Mechanical Engineer, Registered Master Plumber (Plumbing Engineer equivalent), Certified Project Management Professional (PMP), Occupational Health & Safety Management NEBOSH International General Certificate (IG1) passer, ISO QMS Auditor, ISO QMS, ISO EMS, ISO IMS Implementor, and Master in Business Administration (MBA).
2. 2
PL/SQL (Procedural Language for SQL) is
Oracle Corporation's procedural extension for
SQL.
PL/SQL includes procedural language elements
such as conditions and loops, and can handle
exceptions (run-time errors).
The first public version of the PL/SQL definition
was in 1995.
What is PL/SQL?
3. 3
A stored procedure is a set of SQL statements
that can be stored in the database and
executed as a single unit.
It allows you to encapsulate complex
operations, making it easier to manage and
reuse code.
Stored procedures can accept parameters,
perform operations such as data manipulation,
and return results to the caller.
Stored Procedure
5. 5
DELIMITER: By default, MySQL treats
semicolons (;) as the end of a statement. To
define a stored procedure, we change the
delimiter temporarily (e.g., to //) to let MySQL
know that the procedure’s body isn’t ending
with a semicolon.
CREATE PROCEDURE: This is the statement to
create a new stored procedure. You must
define a unique procedure name
(procedure_name).
Stored Procedure (Contd…)
6. 6
Parameters:
◦ IN: Input parameter (default). The caller provides a
value.
◦ OUT: Output parameter. The procedure modifies the
value, and the caller can retrieve it.
◦ INOUT: Input/output parameter. The caller provides
an initial value, and the procedure can modify it.
BEGIN ... END: This block contains the actual
logic of the procedure, including SQL queries
and control structures (like IF, LOOP, WHILE).
Stored Procedure (Contd…)
7. 7
SQL Statements: You can include multiple SQL
statements, such as SELECT, INSERT, UPDATE,
and control structures.
Exception Handling: MySQL provides basic
error handling with DECLARE ... HANDLER.
Stored Procedure (Contd…)
8. 8
Create Procedure:
DELIMITER //
CREATE PROCEDURE GetAllStudent()
BEGIN
SELECT * FROM STUDENTS;
END //
DELIMITER ;
Call Procedure:
CALL GetAllStudent;
Stored Procedure (Contd…)
9. 9
DELIMITER //
CREATE PROCEDURE SetExample()
BEGIN
DECLARE v_discount DECIMAL(5,2);
-- Set a value using SET
SET v_discount = 10.00;
SELECT v_discount;
END //
DELIMITER ;
SET and SELECT
10. 10
DELIMITER //
CREATE PROCEDURE PrintMultiple()
BEGIN
DECLARE s_name VARCHAR(100);
DECLARE s_id INT;
-- Set a value using SET
SET s_name = 'PRIYANKA';
SET s_id = '1'; SELECT CONCAT(s_name,':',s_id) AS
StudentInfo;
END
//DELIMITER ;
CALL PrintMultiple;
SELECT (Contd…)
11. 11
Purpose: The IN parameter allows you to pass
values into the procedure.
Characteristics:
◦ The value of an IN parameter is read-only inside the
procedure, meaning it cannot be modified.
◦ It is the most common type of parameter used to
send input data to the procedure.
IN Parameter
12. 12
DELIMITER //
CREATE PROCEDURE GetUserName(IN user_id
INT)
BEGIN
SELECT name
FROM users
WHERE id = user_id;
END //
DELIMITER ;
CALL GetUserName(1);
IN Parameter (Contd…)
13. 13
Purpose: The OUT parameter allows you to
return values from the procedure.
Characteristics:
◦ The value of an OUT parameter is written by the
procedure and returned to the caller.
◦ You can modify it within the procedure, but its initial
value is not accessible.
OUT Parameter
14. 14
DELIMITER //
CREATE PROCEDURE GetUserEmail(IN user_id
INT, OUT email VARCHAR(255))
BEGIN
SELECT user_email INTO email
FROM users WHERE id = user_id;
END //
DELIMITER ;
SET email =‘’;
CALL GetUserEmail(1, email);
OUT Parameter
15. 15
Purpose:
◦ The INOUT parameter allows you to pass a value into
the procedure and then return a modified value out
of it.
Characteristics:
◦ It behaves like both IN and OUT. You can pass a value
in and also modify and return it.
INOUT Parameter
16. 16
DELIMITER //
CREATE PROCEDURE UpdateBalance(INOUT
user_balance DECIMAL(10,2), IN
deposit_amount DECIMAL(10,2))
BEGIN
SET user_balance = user_balance +
deposit_amount;
END //
DELIMITER ;
INOUT Parameter
17. 17
IF condition THEN
-- statements to execute if condition is
true
ELSEIF condition THEN
-- statements to execute if this condition
is true
ELSE
-- statements to execute if none of the
conditions are true
END IF;
IF…ELSE…
19. 19
BEGIN
DECLARE counter INT DEFAULT 1;
loop_label: LOOP
-- Print the counter value
SELECT counter AS CounterValue;
-- Exit the loop when the counter reaches 5
IF counter >= 5 THEN
LEAVE loop_label;
END IF;
-- Increment the counter
SET counter = counter + 1;
END LOOP;
END //
LOOP (Contd…)
21. 21
BEGIN
DECLARE counter INT DEFAULT 1;
WHILE counter >= 5 DO
-- Print the counter value
SELECT counter AS CounterValue;
-- Increment the counter
SET counter = counter + 1;
END WHILE;
END //
WHILE (Contd…)
23. 23
BEGIN
DECLARE counter INT DEFAULT 1;
REPEAT
-- Print the counter value
SELECT counter AS CounterValue;
-- Increment the counter
SET counter = counter + 1;
UNTIL counter > 5
END REPEAT;
END //
REPEAT…UNTIL (Contd…)
24. 24
A cursor in SQL (and specifically in MySQL) is a
database object that allows you to retrieve and
manipulate rows returned by a query one at a
time. Cursors are especially useful when you
need to process each row individually rather
than working with the entire result set at once.
CURSOR
25. 25
Implicit Cursors: Automatically created by
MySQL when a single-row SQL statement is
executed (e.g., SELECT INTO).
Explicit Cursors: Defined by the user for
queries that return multiple rows. They provide
more control over fetching rows.
Types of Cursors:
26. 26
Declaration: Define a cursor with a specific
SQL query.
Opening: Execute the SQL query and establish
the cursor.
Fetching: Retrieve rows from the cursor one at
a time.
Closing: Release the cursor and free resources.
Cursor Lifecycle:
27. 27
An implicit cursor is automatically created by
the database system when executing SQL
statements that return a single row or multiple
rows.
Unlike explicit cursors, which need to be
explicitly declared, opened, fetched, and closed,
implicit cursors handle these operations
automatically.
They are typically used in SELECT INTO,
INSERT, UPDATE, and DELETE statements.
IMPLICIT CURSOR
28. 28
DELIMITER //
CREATE PROCEDURE GetEmployeeDetails(IN emp_id INT)
BEGIN
DECLARE emp_name VARCHAR(100);
DECLARE emp_salary DECIMAL(10,2);
-- Implicit cursor used in
SELECT INTO SELECT name, salary INTO emp_name, emp_salary
FROM employees
WHERE id = emp_id;
-- Output the employee's details
SELECT emp_name AS Name, emp_salary AS Salary;
END //
DELIMITER ;
IMPLICIT CURSOR (Contd…)
29. 29
Declare the Cursor:
DECLARE cursor_name CURSOR FOR
SELECT_statement;
Open the Cursor:
OPEN cursor_name;
Fetch Rows:
FETCH cursor_name INTO variable1, variable2, ...;
Close the Cursor:
CLOSE cursor_name;
Explicit Cursors
30. 30
DELIMITER //
CREATE PROCEDURE ProcessEmployees()
BEGIN
DECLARE v_emp_id INT;
DECLARE v_first_name VARCHAR(50);
DECLARE done INT DEFAULT FALSE;
-- Declare the cursor for fetching employee details
DECLARE emp_cursor CURSOR FOR
SELECT employee_id, first_name FROM employees;
Explicit Cursors (Contd…)
31. 31
-- Declare a handler for when there are no more rows to
fetch
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done
= TRUE;
-- Open the cursor
OPEN emp_cursor;
-- Loop to fetch rows from the cursor read_loop: LOOP
FETCH emp_cursor INTO v_emp_id, v_first_name;
IF done THEN
LEAVE read_loop;
-- Exit the loop if no more rows
END IF;
Explicit Cursors (Contd…)
32. 32
-- Process each row (for demonstration,
just select)
SELECT v_emp_id AS EmployeeID,
v_first_name AS FirstName;
END LOOP;
-- Close the cursor
CLOSE emp_cursor;
END //
DELIMITER ;
Explicit Cursors (Contd…)
33. 33
DELIMITER //
CREATE PROCEDURE CheckEmployee(IN emp_id INT)
BEGIN
DECLARE v_first_name VARCHAR(50);
DECLARE done INT DEFAULT FALSE;
-- Declare a handler for when no rows are found
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET done = TRUE;
NOT FOUND
34. 34
-- Select the first name of the employee based on
employee ID
SELECT first_name INTO v_first_name
FROM employees
WHERE employee_id = emp_id;
-- Check if a row was found or not
IF done THEN
SELECT 'No employee found with that ID' AS
Message;
NOT FOUND (Contd…)
36. 36
The ROW_COUNT() function returns the
number of rows affected by the last executed
INSERT, UPDATE, or DELETE statement. It’s
useful for checking whether an operation was
successful.
ROW COUNT()
37. 37
DELIMITER //
CREATE PROCEDURE UpdateEmployeeSalary(IN emp_id
INT, IN new_salary DECIMAL(10,2))
BEGIN
-- Update the salary for the specified employee
UPDATE employees
SET salary = new_salary
WHERE employee_id = emp_id;
-- Check the number of affected rows
DECLARE affected_rows INT;
SET affected_rows = ROW_COUNT();
ROW COUNT() (Contd…)
38. 38
-- Output the result
IF affected_rows > 0 THEN
SELECT 'Salary updated successfully.' AS
Message;
ELSE
SELECT 'No employee found with that ID.' AS
Message;
END IF;
END //
DELIMITER ;
ROW COUNT() (Contd…)