Archive for the ‘Oracle’ Category

Execute DDL commands in Oracle PL/SQL

PL/SQL Dynamic SQL

To execute DDL commands we need Dynamic SQL. Dynamic SQL is a programming methodology for generating and running SQL statements at run time. It is useful when writing general-purpose and flexible programs like ad hoc query systems, when writing programs that must run database definition language (DDL) statements, or when you do not know at compilation time the full text of a SQL statement or the number or data types of its input and output variables.

PL/SQL provides two ways to write dynamic SQL:

  •     Native dynamic SQL, a PL/SQL language (that is, native) feature for building and running dynamic SQL statements
  •     DBMS_SQL package, an API for building, running, and describing dynamic SQL statements

Native dynamic SQL code is easier to read and write than equivalent code that uses the DBMS_SQL package, and runs noticeably faster (especially when it can be optimized by the compiler). However, to write native dynamic SQL code, you must know at compile time the number and data types of the input and output variables of the dynamic SQL statement. If you do not know this information at compile time, you must use the DBMS_SQL package.


When You Need Dynamic SQL

In PL/SQL, you need dynamic SQL to run:

  •     SQL whose text is unknown at compile time

    For example, a SELECT statement that includes an identifier that is unknown at compile time (such as a table name) or a WHERE clause in which the number of subclauses is unknown at compile time.

Read more »

Counting DISTINCT over multiple columns in SQL

My database contents

ID CLASS_CODE ROLL_NO NAME
1 IX 1 Jijo K Jose
2 IX 3 James Jacob
3 X 1 Joy Mathew
4 X 2 Sam George
5 IX 2 Miller John
6 X 3 Thomas John

Display values of distinct rows over one column

select distinct(ROLL_NO) from STUDENT;

ROLL_NO  
1
3
2

Read more »

PL/SQL Procedure to INSERT values with EXCEPTION handling

By using PL/SQL we can execute multiple queries at a time. The following example is used to insert student details from STUDENT_TEMP table to STUDENT table and if any error occurred during the insertion process ( like primary key violation, unique key violation etc ) then the corresponding errors will be captured by the EXCEPTION block and will continue the execution.

create or replace
PROCEDURE STUDENT_ADD_PL AS
BEGIN
    FOR REC IN
    (
    SELECT    
        STUDENT_ID,
        ROLL_NO,
        STUDENT_CODE,
        CLASS_ID,
        COLLEGE_NAME,
        PLACE
    FROM STUDENT_TEMP
    )
    LOOP
        BEGIN
            Insert into STUDENT
            (
                STUDENT_ID,
                ROLL_NO,
                STUDENT_CODE,
                CLASS_ID,
                COLLEGE_NAME,
                PLACE

Read more »