Showing posts with label PLSQL. Show all posts
Showing posts with label PLSQL. Show all posts

Saturday, July 23, 2022

PL/SQL Tutorial: Anonymous Blocks, Procedures, Functions, and Packages with Simple Examples

PL/SQL Tutorial: Anonymous Blocks, Procedures, Functions, and Packages

📝 PL/SQL Tutorial: Anonymous Blocks, Procedures, Functions, and Packages with Simple Examples

PL/SQL is a powerful block-structured language used in Oracle databases for procedural programming. It allows developers to write modular, reusable code.


📚 1. PL/SQL Block Structure Overview

PL/SQL code can be categorized as:

  • Anonymous Blocks: Unnamed, not stored in the database, used for quick scripts
  • Named Blocks: Stored in the database, reusable
    • Functions
    • Procedures
    • Packages

Example to get current year:

SELECT TO_CHAR(SYSDATE, 'YYYY') FROM DUAL;
Anonymous blocks are quick, one-time use code blocks. Named blocks like functions, procedures, and packages are stored in the database and can be reused multiple times, making your code cleaner and more maintainable.

🔹 2. Functions

What is a Function?

A function returns a value and can be used in SQL statements or PL/SQL code.

  • Oracle Provided Functions: TO_CHAR(), TO_DATE(), SUM(), AVG(), etc.
  • User Defined Functions: Custom functions for specific logic.
Functions take input parameters, perform calculations or operations, and return a single value. You can use built-in Oracle functions or create your own to encapsulate logic you want to reuse.

Syntax to Create a Function

CREATE [OR REPLACE] FUNCTION function_name [(parameters)] RETURN return_datatype IS | AS
  [declaration_section]
BEGIN
  executable_section
  [EXCEPTION exception_section]
END [function_name];

Example: Calculate Area of Circle

CREATE OR REPLACE FUNCTION AREA_CIRC_FUNC (V_RADIUS INTEGER) RETURN INTEGER IS
  V_AREA NUMBER;
BEGIN
  V_AREA := 3.14 * (V_RADIUS * V_RADIUS);
  RETURN V_AREA;
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('SOME ERROR: ' || SQLERRM);
    RETURN NULL;
END;

How to Run the Function?

1. From PL/SQL Block:

DECLARE
  V_AREA NUMBER;
  V_RADIUS INTEGER := &a;
BEGIN
  V_AREA := AREA_CIRC_FUNC(V_RADIUS);
  DBMS_OUTPUT.PUT_LINE('AREA OF CIRCLE IS: ' || V_AREA);
END;

2. From SQL Query:

SELECT AREA_CIRC_FUNC(100) FROM DUAL;
You can call functions directly within PL/SQL blocks or SQL queries. Functions simplify code by encapsulating reusable logic like calculating the area of a circle.

🔹 3. Procedures

What is a Procedure?

A procedure is a named PL/SQL block that performs an action but does not return a value directly.

Procedures are used when you want to perform tasks such as inserting data, printing messages, or any operation that does not need to return a value.

Basic Procedure Example

CREATE OR REPLACE PROCEDURE PRINT_MSG_PRC IS
BEGIN
  DBMS_OUTPUT.PUT_LINE('HELLO WORLD');
END PRINT_MSG_PRC;

Execute Procedure

EXEC PRINT_MSG_PRC;

or

BEGIN
  PRINT_MSG_PRC;
END;

Procedure with Parameters

IN Parameter (default mode)

CREATE OR REPLACE PROCEDURE ADD_VAL_PRC(X IN NUMBER) IS
  V NUMBER(5);
BEGIN
  V := X + 5000;
  DBMS_OUTPUT.PUT_LINE(V);
END;

Run:

EXEC ADD_VAL_PRC(1000);

Procedure with Multiple IN Parameters

CREATE OR REPLACE PROCEDURE PRINT_EMP_PRC(
  v_empno NUMBER,
  v_sal   NUMBER
) IS
  vname VARCHAR2(10);
BEGIN
  SELECT ename INTO vname FROM empl WHERE empno = v_empno AND sal = v_sal;
  DBMS_OUTPUT.PUT_LINE('Employee name: ' || vname);
END;

Run:

EXEC PRINT_EMP_PRC(7839, 5000);
Procedures can accept parameters to make them flexible. IN parameters allow passing values to the procedure. You can create procedures to perform various tasks using the input parameters.

OUT Parameter Example

CREATE OR REPLACE PROCEDURE PRINT_ENAME_PRC(
  vin_empno IN NUMBER,
  vout_ename OUT VARCHAR2
) IS
BEGIN
  SELECT ename INTO vout_ename FROM empl WHERE empno = vin_empno;
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('SOME ERROR: ' || SQLERRM);
END;

Call with anonymous block:

DECLARE
  V_EMPNO NUMBER := &A;
  V_ENAME VARCHAR2(100);
BEGIN
  PRINT_ENAME_PRC(V_EMPNO, V_ENAME);
  DBMS_OUTPUT.PUT_LINE('Value from procedure: ' || V_ENAME);
END;
OUT parameters allow a procedure to send data back to the caller. This is useful when you want to retrieve values like employee names or calculations.

IN OUT Parameter Example

CREATE OR REPLACE PROCEDURE DER_SAL_PRC(x IN OUT NUMBER) IS
BEGIN
  SELECT sal INTO x FROM empl WHERE empno = x;
END DER_SAL_PRC;

Call:

DECLARE
  V_EMPNO NUMBER := &A;
BEGIN
  DER_SAL_PRC(V_EMPNO);
  DBMS_OUTPUT.PUT_LINE('Salary of employee is: ' || V_EMPNO);
END;
IN OUT parameters act as both input and output. You pass a value in, and the procedure modifies or returns a related value.

🔹 4. Packages

What is a Package?

A package groups related procedures, functions, variables, and other elements together.

Packages help organize your code logically and improve maintainability by grouping related subprograms together. They have two parts: specification (interface) and body (implementation).

Package Specification Syntax

CREATE [OR REPLACE] PACKAGE package_name IS
  -- Public declarations
  [PROCEDURE procedure_name (parameters);]
  [FUNCTION function_name (parameters) RETURN datatype;]
END package_name;
/

Package Body Syntax

CREATE [OR REPLACE] PACKAGE BODY package_name IS
  -- Implementation of procedures and functions
END package_name;
/

Example: Math Package

Package Spec

CREATE OR REPLACE PACKAGE MATH_PKG IS
  FUNCTION AREA_CIRC_FUN (VIN NUMBER) RETURN NUMBER;
  PROCEDURE AREA_SQR_PRC (VIN NUMBER);
END MATH_PKG;
/

Package Body

CREATE OR REPLACE PACKAGE BODY MATH_PKG IS

  FUNCTION AREA_CIRC_FUN (VIN NUMBER) RETURN NUMBER IS
    V_AREA NUMBER;
  BEGIN
    V_AREA := 3.14 * (VIN * VIN);
    RETURN V_AREA;
  EXCEPTION
    WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('ERROR in AREA_CIRC_FUN: ' || SQLERRM);
      RETURN 0;
  END;

  PROCEDURE AREA_SQR_PRC (VIN NUMBER) IS
    V_AREA NUMBER;
  BEGIN
    V_AREA := VIN * VIN;
    DBMS_OUTPUT.PUT_LINE('AREA OF SQUARE IS: ' || V_AREA);
  EXCEPTION
    WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('ERROR in AREA_SQR_PRC: ' || SQLERRM);
  END;

END MATH_PKG;
/

Using the Package

DECLARE
  V_IN_RAD NUMBER := &A;
  V_IN_SIDE NUMBER := &B;
  V_AREA_CIRCLE NUMBER;
BEGIN
  -- Call package function
  V_AREA_CIRCLE := MATH_PKG.AREA_CIRC_FUN(V_IN_RAD);
  DBMS_OUTPUT.PUT_LINE('AREA OF CIRCLE IS: ' || V_AREA_CIRCLE);

  -- Call package procedure
  MATH_PKG.AREA_SQR_PRC(V_IN_SIDE);
END;
/

Summary

Concept Description Example Use Case
Anonymous Block Temporary unnamed PL/SQL block Quick scripts or tests
Function Named block returning a value Calculating areas, business logic
Procedure Named block performing actions, no return Print messages, complex logic
Package Group of related functions and procedures Organizing code by functionality

Happy Coding! 🚀

SQL And PLSQL OVERVIEW

Here is the **HTML version** of your formatted “SQL & PL/SQL Overview” document. It includes structured sections, syntax-highlighted code blocks, and well-organized content. --- ### ✅ \[Downloadable HTML File Option] If you'd like, I can also give you a `.html` file to upload directly to your Blogspot or view offline. Just let me know. --- ### 📄 Full HTML Code: ```html SQL & PL/SQL Overview

SQL & PL/SQL Overview

🔖 Audience

This tutorial is for software professionals who want to learn PL/SQL in a simple and practical way. After finishing this, you'll understand key PL/SQL concepts and be ready to advance further in database development.

✉️ Prerequisites

  • What a database is
  • Programming fundamentals
  • SQL basics

Tip: Knowledge of any programming language is helpful.

What is a Database?

There are two main types of databases:

  1. Relational Databases (RDBMS)
    • Examples: Oracle DB, MySQL, SQL Server, IBM DB2
  2. Non-Relational Databases (NoSQL)
    • Examples: MongoDB, Cassandra, Apache HBase

Oracle DB Versions

Common versions: 8i, 10g, 12c

Key Features

  • Manageability
  • High Availability
  • Performance
  • Security (Roles and Grants)

SQL (Structured Query Language)

  • Pronounced as "SEQUEL"
  • Used for accessing RDBMS
  • Set-oriented: handles multiple records at once
  • Case-insensitive
  • Does not support control structures
  • Can be embedded in other languages

📒 SQL Command Types

1. DDL (Data Definition Language)

Used to define and manage database objects like tables and views.

  • CREATE: Create database objects
  • ALTER: Modify existing objects
  • DROP: Delete objects
  • TRUNCATE: Remove all rows quickly
  • COMMENT: Add descriptive notes
CREATE TABLE NEWTAB (SNO NUMBER(5), SNAME VARCHAR2(10));
ALTER TABLE NEWTAB ADD (ID NUMBER(5));
DROP TABLE NEWTAB;

2. Flashback & Recycle Bin

  • FLASHBACK TABLE: Restore dropped table
  • PURGE: Permanently delete from recycle bin

SQL Data Types

Data TypeDescription
NUMBERStores numeric values (up to 38 digits)
CHARFixed-length strings (up to 2000 bytes)
VARCHAR2Variable-length strings (up to 4000 bytes)
DATEStores date/time values
TIMESTAMPIncludes fractional seconds
TIMESTAMP WITH TIMEZONEStores time zone info
LONG, RAWStores large or binary data
CLOB, BLOB, BFILEStores text, images, or external files
ROWIDStores physical row address
NCLOBSupports multilingual data

PL/SQL Overview

PL/SQL is Oracle's procedural extension to SQL that allows for programming logic and control structures.

Key Features

  • Modular programming
  • Supports loops, IF statements
  • Error handling with EXCEPTION block
  • Tightly integrated with SQL

Block Structure

DECLARE
BEGIN
  -- code
EXCEPTION
END;

Examples

Print Message:

BEGIN
  DBMS_OUTPUT.PUT_LINE('Welcome to PL/SQL');
END;

Using Constants:

DECLARE
  PI CONSTANT NUMBER(5,3) := 3.142;
  radius NUMBER := 5;
  area NUMBER;
BEGIN
  area := PI * radius * radius;
  DBMS_OUTPUT.PUT_LINE('Area: ' || area);
END;

Bind Variables

Allow runtime input for flexible programs.

DECLARE
  A NUMBER := &n;
  B NUMBER := &m;
BEGIN
  DBMS_OUTPUT.PUT_LINE(A + B);
END;

%TYPE and %ROWTYPE

%TYPE: Assigns data type from table column to variable.

vname emp.ename%TYPE;

%ROWTYPE: Assigns all column types from a table.

vrow emp%ROWTYPE;

Nested Blocks

BEGIN
  DECLARE
    v_inner NUMBER := 10;
  BEGIN
    DBMS_OUTPUT.PUT_LINE(v_inner);
  END;
END;

Lexical Units in PL/SQL

  • Identifiers: Names of variables, tables, etc.
  • Reserved Words: BEGIN, END, etc.
  • Delimiters: Special characters like `;`
  • Literals: Fixed values like 'Hello', 123
  • Comments: -- or /* */
``` --- Would you like this in a downloadable `.html` file? I can provide it directly.

Wednesday, July 20, 2022

String Functions with example in SQL ,PLSQL

           -:        String functions in plsql               :--


PL/SQL offers the concatenation operator (||) for joining two strings. The following table provides the string functions provided by PL/SQL .

 

S.No Function & Purpose    
1 ASCII(x);Returns the ASCII value of the character x.    

2 CHR(x); Returns the character with the ASCII value of x.    

3 CONCAT(x, y);Concatenates the strings x and y and returns the appended string.    

4 INITCAP(x);Converts the initial letter of each word in x to uppercase and returns that string.    

5 INSTR(x, find_string [, start] [, occurrence]);Searches for find_string in x and returns the position          at which it occurs.    

7 LENGTH(x);Returns the number of characters in x.    

8 LENGTHB(x);Returns the length of a character string in bytes for single byte character set.    

9 LOWER(x);Converts the letters in x to lowercase and returns that string.    

10 LPAD(x, width [, pad_string]) ;Pads x with spaces to the left, to bring the total length of the string          up to width characters.    

11 LTRIM(x [, trim_string]);Trims characters from the left of x.    

17 NVL(x, value);Returns value if x is null; otherwise, x is returned.    

19 REPLACE(x, search_string, replace_string);Searches x for search_string and replaces it with                    replace_string.    

20 RPAD(x, width [, pad_string]);Pads x to the right.    

21 RTRIM(x [, trim_string]);Trims x from the right.    

22 SOUNDEX(x) ;Returns a string containing the phonetic representation of x.    

25 TRIM([trim_char FROM) x);Trims characters from the left and right of x.    

26 UPPER(x);Converts the letters in x to uppercase and returns that string.  


e.g. 1 


set serveroutput on;

  DECLARE 

   v_greet varchar2(100) := 'Good Morning !!!'; 

BEGIN 

   dbms_output.put_line(UPPER(v_greet)); 

    

   dbms_output.put_line(LOWER(v_greet)); 

    

   dbms_output.put_line(INITCAP(v_greet)); 

    

   /* retrieve the first character in the string */ 

   dbms_output.put_line ( SUBSTR (v_greet, 1, 1)); 

    

   /* retrieve the last character in the string */ 

   dbms_output.put_line ( SUBSTR (v_greet, -1, 1)); 

    

   /* retrieve five characters,  

      starting from the seventh position. */ 

   dbms_output.put_line ( SUBSTR (v_greet, 7, 5)); 

    

   /* retrieve the remainder of the string, 

      starting from the second position. */ 

   dbms_output.put_line ( SUBSTR (v_greet, 2)); 

     

   /* find the location of the first "e" */ 

   dbms_output.put_line ( INSTR (v_greet, 'e')); 

END; 

/




E.g 2 :


DECLARE 

   VGREET varchar2(30) := '......Hello World.....'; 

BEGIN 

   dbms_output.put_line(RTRIM(VGREET,'.')); 

dbms_output.put_line(LTRIM(VGREET, '.')); 

dbms_output.put_line(TRIM( '.'from VGREET)); 

END;


Wednesday, June 1, 2022

JSON support in 12c

 JSON SUPPROT IN ORACLE 12C 


Oracle has started json support from 12c version onwards . JSON is used nowadays more populalry for data transfer among different subsystems similar to XML. 

below are some examples to understand the json support.

SET SERVEROUTPUT ON;
DECLARE
    TYPE nt_fName   IS TABLE OF VARCHAR2 (20);
    TYPE nt_JName   IS TABLE OF VARCHAR2 (20);
    
    fname   nt_fName;
    LJOB   nt_JName;
BEGIN
    SELECT Ename, JOB
        BULK COLLECT INTO fName, LJOB 
    FROM empL; 
        
        --Print values from the collection--
    FOR idx IN 1..fName.COUNT
    LOOP
        DBMS_OUTPUT.PUT_LINE (idx||' - EMP NAME IS : '||fName (idx) ||' AND JOB : '||LJOB (idx));
    END LOOP;
END;







---------------------JSON --------------------

SELECT JSON_OBJECT('ENAME ' VALUE ENAME ) FROM EMPL---

SELECT JSON_OBJECTAGG('ENAME' VALUE ENAME ) FROM EMPL--

SELECT JSON_ARRAY(ENAME ) FROM EMPL --

SELECT JSON_ARRAYAGG(ENAME) FROM EMPL

/

--GENERATE JSON DATA FRRMAT FOR DEPT AND EMPLOYEES WORKING IN THOSE DEPT

SELECT JSON_OBJECTAGG(D.DNAME
       VALUE JSON_ARRAY(E.ENAME))
   FROM EMPL E, DEP D
   WHERE E.DEPNO=D.DEPNO
   GROUP BY D.DNAME


/

SELECT JSON_OBJECTAGG(D.DNAME
       VALUE JSON_ARRAYAGG(E.ENAME))
   FROM EMPL E, DEP D
   WHERE E.DEPNO=D.DEPNO
   GROUP BY D.DNAME


--- dynamic sql---  EMPL , DEP 
SET SERVEROUTPUT ON;
DECLARE
SQL_STMT VARCHAR2(1000);
 EMP_TOT VARCHAR2(1000);
 v_qry varchar2(100);
BEGIN
v_qry := &a;
SQL_STMT := 'SELECT COUNT(*) FROM  ' ||v_qry; --always it shud be insingle quotes
EXECUTE IMMEDIATE SQL_STMT INTO EMP_TOT;
DBMS_OUTPUT.PUT_LINE('TOTAL rowcount from table '|| v_qry || ' is : '||EMP_TOT);
END;
/

Wednesday, May 11, 2022

Cuesors and Types of Cursors

 CURSORS IN PLSQL WITH SIMPLE                                         EXAMPLES


-----------------------------CURSORS--------------------------
 
 CURSOR :
  
-->> WHENEVER A SQL AUERY WHICH RETRIVES MORE THAN  ONE ROW , TO PROCESS THOSE RECORDS/ROWS WE USE CURSORS.
  >>CONTEXT AREA OF MEMORY WHERE QUERY RECORDS ARE SAVED.
 
 
 -----------
 
 DECLARE
 V_EMPNO EMPL.EMPNO%TYPE;
 V_SAL   EMPL.SAL%TYPE;
 V_HIREDATE EMPL.HIREDATE%TYPE;
 BEGIN
 SELECT EMPNO,SAL,HIREDATE 
 INTO V_EMPNO,V_SAL,V_HIREDATE --ONLY ONE ROW
 FROM EMPL
 WHERE  ROWNUM<10;
 

 DBMS_OUTPUT.PUT_LINE('ID  OF       EMPLOYE IS :'||V_EMPNO);
 DBMS_OUTPUT.PUT_LINE('SALARY  OF   EMPLOYE IS :'||V_SAL);
 DBMS_OUTPUT.PUT_LINE('HIREDATE  OF EMPLOYE IS :'||V_HIREDATE);
 END;
 
 -----------------------
 
  --TYPES OF CUSRSORS
    1. IMPLICIT CURSORS: >> SYSTEM DEFINED
    2. EXPLICIT CURSORS  >> USER DEFINED 
    
    
  -------------------  
 
 
DECLARE
  CURSOR C IS    SELECT *  FROM EMPL;
BEGIN
  FOR I IN c
  LOOP
    dbms_output.put_line('EMPLOYEE NAME IS :  '||i.ename || ' ::EMPLOYEE ID IS :'|| I.EMPNO ||' ::SALARY IS : '||I.SAL);
  END LOOP;
END;
/

 
 
 
 -------------------------------
 
 
 
 
DECLARE
CURSOR EMP_CUR IS SELECT ENAME, EMPNO FROM EMPL; --DECLARE
V_CUR EMP_CUR%ROWTYPE;
BEGIN
 OPEN EMP_CUR;  --2. OPEN THE CURSORS
 FETCH EMP_CUR INTO V_CUR;
 LOOP 
 EXIT WHEN EMP_CUR%NOTFOUND 
 DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME IS : ' || V_CUR.ENAME || ':: EMP ID IS : '||V_CUR.EMPNO );
 END LOOP;
 END;
 
 
 /
 
 DECLARE
  CURSOR c  IS    SELECT ename FROM empl; --DECLARE
  vname c%rowtype;
BEGIN
  OPEN c; --2. OPEN THE CURSORS
  loop
    fetch c INTO vname; -- FETCH CURSOR 
    exit  WHEN c%notfound; 
    dbms_output.put_line(vname.ename);
  END loop;
  CLOSE C;          --4. CLOSE CURSOR
END;
/


--CURSOR FOR LOOPS:
--OPEN , FETCH  AND CLOSE THE CURSR INTERNALLY...
--WE NEED NOT INITIALIZE VARIABLE AS WELL.


 --WAY001
 DECLARE
  CURSOR c
  IS
    SELECT ename FROM empl;
  Vname c%rowtype;
BEGIN
  OPEN c;
  LOOP
    FETCH c INTO vname;
    EXIT
  WHEN c%notfound;
    Dbms_output.put_line(vname.ename);
  END LOOP;
END;
/


--WAY _002
  DECLARE
  CURSOR c  IS    SELECT ename FROM empl; --DECLARE 
BEGIN  
  FOR I IN  C LOOP
  DBMS_OUTPUT.PUT_LINE('NAME OF EMPLOYEE IS :'||I.ENAME);
  END LOOP;
  
END;

--WAY _003
 
BEGIN  
  FOR I IN ( SELECT ename FROM empl) LOOP
  DBMS_OUTPUT.PUT_LINE('NAME OF EMPLOYEE IS :'||I.ENAME);
  END LOOP;
  
END;
  
 / 
 --WAY001
 DECLARE
  CURSOR c
  IS
    SELECT ename FROM empl;
  Vname c%rowtype;
BEGIN
  OPEN c;
  LOOP
    FETCH c INTO vname;
    EXIT
  WHEN c%notfound;
    Dbms_output.put_line(vname.ename);
  END LOOP;
END;
/

 ----------------------------------------------PARAMETERISED CURSORS:-------------------------------
 
 
 ----------------------------------------------PARAMETERISED CURSORS:-------------------------------
 
 A CURSOR WHICH CAN ACCEPT THE PARAMETER IS CALLED AS PARAMETERISED CURSOR.
 
  E.G 
  
  
  DECLARE
  CURSOR c (X NUMBER,V_ENAME VARCHAR2)  IS    SELECT HIREDATE,SAL  FROM empl WHERE EMPNO = X AND ENAME = V_ENAME; --DECLARE 
  VAR_1 NUMBER;
  VAR_2 VARCHAR2(100);
BEGIN  
 VAR_1 := &a;
 VAR_2 := &B;
 
  FOR I IN  C (VAR_1 , VAR_2) LOOP
  DBMS_OUTPUT.PUT_LINE('HIREDATE  OF EMPLOYEE IS :'||I.HIREDATE);
  DBMS_OUTPUT.PUT_LINE('SALARY  OF EMPLOYEE IS :'||I.SAL);
  END LOOP;
  
END;

/


Saturday, January 1, 2022

Performance Tuning Tips in Oracle

 TIPS FOR PERFORMANCE TUNING 


1. try to Analyze cost of the query using explain plan






2. using explain plan try to find out the cost of query and find out which join is taking more cost , that is taking more time , so try to rewrite that join or expression.

3. Try to use exists () , instead of in () / like expression.

4. try to Add indexes on the id columns

5. If creating indexes doesnot work then try creating functional index which is more of related to a expression of a query join

6. try to use partition by clause.

7. Try to avoid the full table scans.



query to get Shipment number based on Order number

 SELECT DISTINCT     wnd.delivery_name,     wnd.actual_ship_date,     wdd.sales_order_number FROM     wsh_new_deliveries       wnd,     wsh_...

Popular Posts