Dbms 5,6,7 (1) - Removed
Dbms 5,6,7 (1) - Removed
Aim:
To implement queries and manage the database using SQL Programming with user defined functions
and procedures.
Procedure:
A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design'. A subprogram can be invoked
by another subprogram or program which is called the calling program.
A subprogram can be created −
At the schema level
Inside a package
Inside a PL/SQL block
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters. PL/SQL
provides two kinds of subprograms −
Functions − These subprograms return a single value; mainly used to compute and return a value.
Procedures − These subprograms do not return a value directly; mainly used to perform an action.
Parts of a PL/SQL Subprogram
Each PL/SQL subprogram has a name, and may also have a parameter list. Like anonymous PL/SQL
blocks, the named blocks will also have the following three parts −
S.No Parts & Description
Declarative Part
It is an optional part. However, the declarative part for a subprogram does not start with the
1 DECLARE keyword. It contains declarations of types, cursors, constants, variables,
exceptions, and nested subprograms. These items are local to the subprogram and cease to
exist when the subprogram completes execution
2 Executable Part
This is a mandatory part and contains statements that perform the designated action.
Exception-handling
3
This is again an optional part. It contains the code that handles run-time errors.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
721222104002 48
{IS | AS}
BEGIN
< procedure_body > END procedure_name;
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the parameters. IN represents the
value that will be passed from outside and OUT represents the parameter that will be used to
return a value outside of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on the screen when
executed.
When the above code is executed using the SQL prompt, it will produce the following result −
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greet;
Hello World
721222104002 49
The procedure can also be called from another PL/SQL block −
BEGIN
greet;
END;
/
The above call will display –
You can drop the greetings procedure by using the following statement −
721222104002 50
When the above code is executed at the SQL prompt, it produces the following result –
When the above code is executed at the SQL prompt, it produces the following result −
Square of (5): 25
PL/SQL procedure successfully completed.
721222104002 51
Step 1
The following will create a table in Oracle. For example I will create a table for customer details.
NAME VARCHAR2(20),
GENDER VARCHAR2(7),
ADDRESS VARCHAR2(100));
Step 2
After creating the table, write a Stored Procedure for an insert:
1. CREATE OR REPLACE PROCEDURE INSERTcustomer (
p_name CUSTOMER.NAME%TYPE,
p_gender CUSTOMER.GENDER%TYPE,
4. p_address CUSTOMER.ADDRESS%TYPE)
IS
BEGIN
INSERT INTO CUSTOMER (NAME, GENDER, ADDRESS)
Step 3
Stored Procedure for an update:
p_name IN CUSTOMER.NAME%TYPE,
p_gender IN CUSTOMER.GENDER%TYPE,
p_address IN CUSTOMER.ADDRESS%TYPE)
IS
BEGIN
UPDATE CUSTOMER SET NAME=p_name, GENDER=p_gender, ADDRESS=p_address WHERE NAME=p_name;
COMMIT;
END;
10. /
Step 4
p_name IN CUSTOMER.NAME%TYPE,
p_customer_display OUT SYS_REFCURSOR)
IS
5. BEGIN
OPEN p_customer_display for SELECT NAME, GENDER, ADDRESS FROM CUSTOMER WHERE NAME=p_name;
END;
721222104002 52
Step 5
Stored Procedure for a delete:
p_name IN CUSTOMER3.NAME%TYPE)
IS
BEGIN
DELETE FROM CUSTOMER WHERE NAME=p_name;
END;
/
PL/SQL - Functions
Where,
function-name specifies the name of the function.
The RETURN clause specifies the data type you are going to return from the function.
The AS keyword is used instead of the IS keyword for creating a standalone function.
Example
The following example illustrates how to create and call a standalone function. This function returns
the total number of CUSTOMERS in the emp table.
CUSTOMERS table
Select
721222104002 53
* from customers;
+ + + + + +
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Function created.
Calling a Function
While creating a function, you give a definition of what the function has to do. To use a function, you will
have to call that function to perform the defined task. When a program calls a function, the program control
is transferred to the called function.
A called function performs the defined task and when its return statement is executed or when the last end
statement is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name and if the
function returns a value, then you can store the returned value. Following program calls the function
totalCustomers from an anonymous block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
721222104002 54
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function that
computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
ELSE Z:= y;
END;
c := findMax(a, b);
When the above code is executed at the SQL prompt, it produces the following
721222104002 55
User Defined Functions
⚫ User-defined functions are functions that you use to organize your code in the body of a policy.
⚫ Once you define a function, you can call it in the same way as the built-in action and parser functions.
⚫ Variables that are passed to a function are passed by reference, rather than by value.
Syntax:
CREATE OR REPLACE FUNCTION function_name(p1 type, p2 type)
RETURNS type
AS
BEGI
N
-- logic
Example:
END;
LANGUAGE PLPGSQL;
Calling a function:
Syntax:
SELECT function_name(20);
Example:
SELECT inc(20);
Result:
Thus the database created successfully. Procedures and Functions are executed successfully.
721222104002 56
Ex.No : 7 Execute complex transactions and realize DCL and TCL commands.
AIM
To execute complex transactions and realize DCL and TCL commands.
GRANT Command
It is employed to grant a privilege to a user. GRANT command allows specified users to perform specified tasks
Syntax
REVOKE Command
It is employed to remove a privilege from a user. REVOKE helps the owner to cancel previously granted
permissions.
Syntax
REVOKE privilege_name on objectname from user; Here,
• privilege names are SELECT,UPDATE,DELETE,INSERT,ALTER,ALL
• objectname is table name
• user is the name of the user whose privileges are removing
Example
REVOKE SELECT, UPDATE ON employees TO Bhanu
TCL Commands
Transaction Control Language (TCL) commands are used to manage transactions in the database. A single
unit of work in a database is formed after the consecutive execution of commands is known as a transaction.
721222104002 57
There are certain commands present in SQL known as TCL commands that help the user manage the
transactions that take place in a database.
COMMIT, ROLLBACK and SAVEPOINT are the most commonly used TCL commands in SQL.
COMMIT Command
COMMIT command in SQL is used to save all the transaction-related changes permanently to the
disk. Whenever DDL commands such as INSERT, UPDATE and DELETE are used, the changes made
by these commands are permanent only after closing the current session. So before closing the session,
one can easily roll back the changes made by the DDL commands. Hence, if we want the changes to
be saved permanently to the disk without closing the session, we will use the commit command.
Syntax SQL>COMMIT;
Example:
To create a table named t_school, we will execute the following query:
mysql> CREATE TABLE t_school(ID INT, School_Name VARCHAR(40), Number_Of_Students INT,
Number_Of_Teachers INT, Number_Of_Classrooms INT, EmailID VARCHAR(40));
Now, we will execute the following query to insert multiple records at the same time in the t_school table.
mysql> INSERT INTO t_school(ID, School_Name, Number_Of_Students, Number_Of_Teachers, Num
ber_Of_Classrooms, EmailID) VALUES(1, "Boys Town Public School", 1000, 80, 12, "btps15@gmail.c
om"), (2, "Guru Govind Singh Public School", 800, 35, 15, "ggps25@gmail.com"), (3, "Delhi Public Sch
ool", 1200, 30, 10, "dps101@gmail.com"), (4, "Ashoka Universal School", 1110, 40, 40, "aus17@gmail.c
om"), (5, "Calibers English Medium School", 9000, 31, 50, "cems@gmail.com");
721222104002 58
We will now execute the SELECT query to verify the execution of the INSERT INTO query executed
above.
mysql> SELECT *FROM t_school;
After executing the SELECT query on the t_school table, you will get the following output:
The output of the SELECT query shows that all the records are inserted successfully. We will execute the
COMMIT command to save the results of the operations carried on the t_school table. mysql>
COMMIT;
Autocommit is by default enabled in MySQL. To turn it off, we will set the value of autocommit as 0.
mysql> SET autocommit = 0;
721222104002 59
MySQL, by default, commits every query the user executes. But if the user wishes to commit only the
specific queries instead of committing every query, then turning off the autocommit is useful.
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that point
whenever required.
Syntax
Savepoint Savepoint_name;
ROLLBACK command
This command restores the database to last committed state. It
is also used with SAVEPOINT command to jump to a savepoint in an ongoing
transaction. If we have used the UPDATE command to make some changes into the database, and
realise that those changes were not required, then we can use the ROLLBACK command to rollback
those changes, if they were not committed using the COMMIT command.
Syntax
Rollback to Savepoint_name;
Example
BEGIN / START TRANSACTION command is used to start the transaction. mysql>
START TRANSACTION;
721222104002 60
As we know, the SAVEPOINT command in SQL is used to save the different parts of the same transaction
using different names. Consider till this point as one part of our transaction. We will save this part using a
savepoint named Insertion. mysql> SAVEPOINT Insertion;
Now, we will execute the update command on the t_school table to set the Number_Of_Students as 9050
for the record with ID 5.
mysql> UPDATE t_school SET Number_Of_Students = 9050 WHERE ID = 5;
To verify that the record with ID 5 now has the Number_Of_Students as 9050, we will execute the
SELECT query.
mysql> SELECT *FROM t_school;
After executing the SELECT query on the t_school table, you will get the following output:
The output of the SELECT query shows that the record with ID 5 is updated successfully.
Consider the update operation as one part of our transaction. We will save this part using a savepoint
named Updation.
mysql> SAVEPOINT Updation;
721222104002 61
Suddenly, our requirement changed, and we realized that we had updated a record that was not supposed to
be. In such a scenario, we need to roll back our transaction to the savepoint, which was created prior to the
execution of the UPDATE command. mysql> ROLLBACK TO Insertion;
We didn't need the updation carried on the record. Hence, we have rolled back to the savepoint named
Insertion.
For confirming that we have got the same t_school table that we had before carrying out
the updation operation, we will again execute the SELECT query. mysql> SELECT
*FROM t_school;
The SELECT query output confirms that the transaction is now successfully rolled back to the savepoint
'Insertion'.
RESULT:
Thus we executed the complex transactions using DCL and TCL commands successfully.
721222104002 62