DBMS - Iv Unit
DBMS - Iv Unit
UNIT IV
2 marks:
1. Give two advantages of PL/SQL over SQL.
• There are no variables in SQL whereas PL/SQL has variables constraints, data
types, etc.
• PL/SQL offers high processing speed while performing manipulation of large
volumes of data. This can’t be achieved with SQL.
17. What is the command used to read the cursor data? Give syntax.
29. What the package used to display the message on the screen? Give Syntax.
The DBMS_OUTPUT is a built-in package that enables you to display output, debugging
information, and send messages from PL/SQL blocks, subprograms, packages, and triggers.
Syntax:
Dbms_output.put_line(‘Hello Reader!’);.
1. Declaration section
2. Execution section
3. Exception-Handling section
The below picture illustrates the different PL/SQL block and their section order.
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This is the section
in which the declaration of variables, cursors, exceptions, subprograms, pragma instructions and
collections that are needed in the block will be declared. Below are few more characteristics of
this part.
Execution Section
Execution part is the main and mandatory part which actually executes the code that is written
inside it. Since the PL/SQL expects the executable statements from this block this cannot be an
empty block, i.e., it should have at least one valid executable code line in it.
Below are few more characteristics of this part.
Exception-Handling Section
The exception is unavoidable in the program which occurs at run-time and to handle this Oracle
has provided an Exception-handling section in blocks. This section can also contain PL/SQL
statements. This is an optional section of the PL/SQL blocks.
Example:
2. What are different types of literals? Explain with example.
SQL Literals
There are four kinds of literal values supported in SQL. They are : Character string, Bit string,
Exact numeric, and Approximate numeric. These are explained as following below.
1. Character string :
Character strings are written as a sequence of characters enveloped in single quotes.
the only quote character is delineate at intervals a personality string by 2 single quotes. Some
example of character strings are : ‘My String’ , ‘I love GeeksForGeeks’ , ‘16378’
2. Bit string :
A bit string is written either as a sequence of 0s and 1s enveloped in single quotes and
preceded by the letter ‘B’ or as a sequence of positional representation system digits
enveloped in single quotes and preceded by the letter X’ some examples are given below :
B’10001011′
B’1′
B’0′
X’C 5′
X’0′
3. Exact numeric :
These literals ar written as a signed or unsigned decimal variety probably with
mathematical notation. Samples of actual numeric literals are given below :
8
80.00
+88.88
-88.88
4. Approximate numeric :
Approximate numeric literals are written as actual numeric literals followed by the letter ‘E’,
followed by a signed or unsigned number. Some example are :
6E6
66.6E6
+66E-6
-6.66E-8
IF...ELSE STATEMENT:-
The IF statement associates a condition with a sequence of statements enclosed by the keywords
THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition is
FALSE or NULL, then the IF statement does nothing.
Syntax
IF condition THEN
{...statements to execute when condition is TRUE...}
END IF;
Where condition is a Boolean or relational condition and S is a simple or compound statement.
Example:
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
IF( a < 20 ) THEN
dbms_output.put_line('a is less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
If the Boolean expression condition evaluates to true, then the block of code inside the if statement
will be executed. If the Boolean expression evaluates to false, then the first set of code after the
end of the if statement (after the closing end if) will be executed.
To control transactions Oracle does not made permanent any DML statements unless you commit
it. If you don’t commit the transaction and power goes off or system crashes then the transaction
is roll backed.
COMMIT
To make the changes done in a transaction permanent issue the COMMIT statement.
Syntax:
COMMIT [WORK] [COMMENT ‘your comment’];
WORK is optional.
COMMENT is also optional, specify this if you want to identify this transaction in data
dictionary DBA_2PC_PENDING.
Example: insert into emp (empno,ename,sal) values (101,’Abid’,2300);
commit;
ROLLBACK
To rollback the changes done in a transaction give rollback statement. Rollback restore the state
of the database to the last commit point.
Example :
delete from emp;
rollback; /* undo the changes */
6. What is a cursor ? Explain different types of cursor.
Cursor is a Temporary Memory or Temporary Work Station. Whenever DML statements are
executed, a temporary work area is created in the system memory. A cursor can have more than
one row, but processing wise only 1 row is taken into account. They can be used well with DML
statements like Update, Insert and Delete. In PL/SQL, two different types of cursors are available.
In PL/SQL, two different types of cursors are available.
(i) Implicit cursors
(ii) Explicit cursors
Explicit cursors
Explicit cursors are defined by the programmers to have more control area on the context area.
It has to be defined in the declaration section of the PL/SQL Block. Usually, It is defined on a
SELECT Statement and it returns more than one row as output. We can iterate over the rows of
data and perform the required operations.
Syntax:
CURSOR cursor_name IS select_statement;
Steps involved in creating explicit cursors:
• Cursor Declaration for initializing the memory
CURSOR <cursorName> IS
SELECT <Required fields> FROM <tableName>;
• Cursor Opening to allocate the memory
OPEN <cursorName>;
• Cursor Fetching to retrieve the data
FETCH <cursorName> INTO <Respective columns>
• Cursor Closing to release the allocated memory
CLOSE <cursorName>;
Execute the following program to retrieve the customer name and address.
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || '
' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Implicit Cursors
The implicit cursors are automatically generated by Oracle while an SQL statement is executed, if you
don't use an explicit cursor for the statement.These are created by default to process the statements when
DML statements like INSERT, UPDATE, DELETE etc. are executed.
Orcale provides some attributes known as Implicit cursor's attributes to check the status of DML
operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.
Let's execute the following program to update the table and increase salary of each customer by
5000.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers
updated ');
END IF;
END;
/
7. Explain use of parameterised cursor with example.
Parameterized cursor pass the parameters into a cursor and use them in to query. An explicit
cursor may accept a list of parameters. Each time you open the cursor, you can pass different
arguments to the cursor, which results in different result sets.
Syntax:
CURSOR cursor_name (parameter_list)
IS
cursor_query;
In the cursor query, each parameter in the parameter list can be used anywhere which a constant is used.
The cursor parameters cannot be referenced outside of the cursor query.
To open a cursor with parameters, you use the following syntax:
OPEN cursor_name (value_list);
Example:
DECLARE
cursor c(no number) is select * from emp_information
where emp_no = no;
tmp emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No: '||tmp.emp_no);
dbms_output.put_line('EMP_Name: '||tmp.emp_name);
dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
END Loop;
CLOSE c;
END;
/
Output:
EMP_No: 4
EMP_Name: Zenia Sroll
EMP_Dept: Web Developer
EMP_Salary: 42k
8. Explain with syntax and example, how to create a cursor and read the records from a
cursor.
Cursors can be explicitly created on a SELECT Statement which returns more than one row.
Syntax:
CURSOR cursor_name IS select_statement;
host_cursor_variable_name
A cursor variable declared in a PL/SQL host environment and passed to PL/SQL as a bind
variable. The datatype of the host cursor variable is compatible with the return type of any
PL/SQL cursor variable. Host variables must be prefixed with a colon.
%ISOPEN Attribute
A cursor attribute that can be appended to the name of a cursor or cursor variable. If a cursor is
open, cursor_name%ISOPEN returns TRUE; otherwise, it returns FALSE.
%NOTFOUND Attribute
A cursor attribute that can be appended to the name of a cursor or cursor variable. Before the first
fetch from an open cursor, cursor_name%NOTFOUND returns NULL. Thereafter, it returns
FALSE if the last fetch returned a row, or TRUE if the last fetch failed to return a row.
%ROWCOUNT Attribute
A cursor attribute that can be appended to the name of a cursor or cursor variable. When a cursor
is opened, %ROWCOUNT is zeroed. Before the first
fetch, cursor_name%ROWCOUNT returns 0. Thereafter, it returns the number of rows fetched
so far. The number is incremented if the latest fetch returned a row.
10. Write a note on error handling in PL/SQL.
In PL/SQL, an error condition is called an exception. Exceptions can be internally defined (by the
runtime system) or user defined. Examples of internally defined exceptions include division by
zero and out of memory.
When an error occurs, an exception is raised. That is, normal execution stops and control
transfers to the exception-handling part of your PL/SQL block or subprogram. Internal
exceptions are raised implicitly (automatically) by the run-time system. User-defined exceptions
must be raised explicitly by RAISE statements, which can also raise predefined exceptions.
To handle raised exceptions, you write separate routines called exception handlers. After an
exception handler runs, the current block stops executing and the enclosing block resumes with
the next statement. If there is no enclosing block, control returns to the host environment.
Exceptions are raised by the database server automatically whenever there is any internal database error,
but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is
the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-
defined exception must be declared and then raised explicitly, using either a RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated
by a program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT
INTO statement returns no rows.
13. Explain with example how to create a procedure / function and use it.
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.
o Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.
In this example, we are going to insert record in user table. So you need to create user table first.
Table creation:
create table user(id number(10) primary key,name varchar2(100));
Procedure Code:
• BEGIN, EXCEPTION and END are keywords used to indicate different sections of
the procedure being created.
When you want to create a procedure or function, you have to define parameters .There is
three ways to pass parameters in procedure:
OUT Parameter:
• This parameter is used for getting output from the subprograms.
• It is a read-write variable inside the subprograms. Their values can be changed inside
the subprograms.
• In the calling statement, these parameters should always be a variable to hold the
value from the current subprograms.
IN OUT Parameter:
• This parameter is used for both giving input and for getting output from the
subprograms.
• It is a read-write variable inside the subprograms. Their values can be changed inside
the subprograms.
• In the calling statement, these parameters should always be a variable to hold the
value from the subprograms.
17. Explain various forms of if...endif structures with syntax and example.
18. Explain various looping statements of PL/SQL with syntax.
19. Explain various commands/statements required to open , process and close the
explicit cursor with syntax and example.
The explicit cursor is programmer defined cursor which is used to process set of select
statements together.
Opening the Cursor
The OPEN statement of cursor will execute the query associated with the cursor. When you
use the OPEN statement following will happen :
•Identifies the active set . The active set is set of rows which satisfies search criteria.
21. With syntax and example explain how a stored procedure is created and executed in
PL/SQL ?
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one
or more specific tasks. It is just like procedures in other programming languages.
The procedure contains a header and a body.
•Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.
•Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.
PL/SQL Create Procedure
Syntax for creating procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
Executable_section
[EXCEPTION
Exception_section]
END [procedure_name];
Table creation:
Create table user(id number(10) primary key,name varchar2 *Now
write the procedure code to insert record in user table.
Procedure Code:
22. With syntax and example explain how a function is created and executed in PL/SQL?
Ans: Function can be used as a part of SQL expression i.e. we can use them with
select/update/merge commands. One most important characteristic of a function is that,
unlike procedures, it must return a value.
Syntax: Creating a function
CREATE [OR REPLACE] FUNCTION function_name [parameters] [(parameter_name [IN
| OUT | IN OUT] type [, …])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body > END
[function_name]; Here:
Function_name: specifies the name of the function.[OR REPLACE] option allows modifying
an existing function.
•The optional parameter list contains name, mode and types of the parameters.
•IN represents that value will be passed from outside and OUT represents that this parameter
will be used to return a value outside of the procedure.
The function must contain a return statement:
•RETURN clause specifies that data type you are going to return from the function.
23. With syntax and example explain how a package is created and executed in
PL/SQL?
A package is a way of logically storing the subprograms like procedures, functions, exception
or cursor into a single common unit.
create a PL/SQL Package
Following are the steps to declare and use a package in PL/SQL code block:
STEP 1: Package specification or declaration.
syntax:
CREATE OR REPLACE PACKAGE <package_name> IS/AS
FUNCTION <function_name> (<list of arguments>)
RETURN <datatype>;
PROCEDURE <procedure_name> (<list of arguments>);
Code statements
END <package_name>; Where,
•It contains the subprogram bodies containing executable statements for which package has
been created.
syntax:
CREATE OR REPLACE PACKAGE BODY <package_name> IS/AS
FUNCTION <function_name> (<list of arguments>) RETURN <datatype>IS/AS
Executable statements;
EXCEPTION
Error handling statements;
END <function_name>;
PROCEDURE <procedure_name> (<list of arguments>)IS/AS
Executable statements;
EXCEPTION
DECLARE
c_id customers.id%type := 8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
After the execution of above code at SQL Prompt, it produces the following result:
The above program should show the name and address of a customer as result whose ID is
given. But there is no customer with ID value 8 in our database, so the program raises the
runtime exception NO_DATA_FOUND, which is captured in EXCEPTION block.