Constants in PL/SQL

Definition:

  • Constants are user defined identifier whose values remain unchanged throughout the program
  • Constants needs to be declared prior to their use like variables in PL/SQL
  • Constants can declared only in the declaration section in the PL/SQL block.

Syntax:

  1. Constant_name CONSTANT data_type(data_width) := value;

Explanation:

  •    Constant_name valid constant name (user defined)
  •    Constant_name followed CONSTANT keyword
  •    Data_type of the value
  •    := Assignment operator
  •    Value (constant value)

Note: You must initialize the constant at the DECLARATION section. You cannot initialize the constant anywhere else.

Example:

  1. DECLARE

       var_pi   CONSTANT NUMBER (7,6) := 3.1415;

    BEGIN

       DBMS_OUTPUT.put_line (var_pi);

    END;

Output:

Attributes of constants:

                 1.    Default

               2.    Not Null

Default:

Here, we are used DEFAULT keyword Instead of assignment operator (:=) for initializing the constant.

  1. DECLARE

       var_pi   CONSTANT NUMBER (7, 6) DEFAULT 3.1415;

    BEGIN

       DBMS_OUTPUT.put_line (var_pi);

    END;

Output:

Not Null:

       NOT NULL for preventing Null values.

  1. DECLARE

       var_pi   CONSTANT NUMBER (7, 6) NOT NULL DEFAULT 3.1415;

    BEGIN

       DBMS_OUTPUT.put_line (var_pi);

    END;

Output:


Example for Initialize constant in the BEGIN section:

  1. DECLARE

       var_pi   CONSTANT NUMBER (7, 6) ;

    BEGIN

       var_pi := 3.1415;

       DBMS_OUTPUT.put_line (var_pi);

    END;

Explanation:

  Above type of declaration and initialization is legally accepted in PL/SQL variable but comes to constant this is not accepted by the compiler.

The error report is,



 

 

Share:

No comments:

Post a Comment

Popular Posts

Search This Blog

Powered by Blogger.

Blog Archive

Service Support

Need our help to Learn or Post New Concepts Contact me

Blog Archive

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me