Category: plsql

  • Khóa học miễn phí PL/SQL – Overview nhận dự án làm có lương

    PL/SQL – Overview



    The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as procedural extension language for SQL and the Oracle relational database. Following are certain notable facts about PL/SQL −

    • PL/SQL is a completely portable, high-performance transaction-processing language.

    • PL/SQL provides a built-in, interpreted and OS independent programming environment.

    • PL/SQL can also directly be called from the command-line SQL*Plus interface.

    • Direct call can also be made from external programming language calls to database.

    • PL/SQL”s general syntax is based on that of ADA and Pascal programming language.

    • Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2.

    Features of PL/SQL

    PL/SQL has the following features −

    • PL/SQL is tightly integrated with SQL.
    • It offers extensive error checking.
    • It offers numerous data types.
    • It offers a variety of programming structures.
    • It supports structured programming through functions and procedures.
    • It supports object-oriented programming.
    • It supports the development of web applications and server pages.

    Advantages of PL/SQL

    PL/SQL has the following advantages −

    • SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements in PL/SQL blocks.

    • PL/SQL allows sending an entire block of statements to the database at one time. This reduces network traffic and provides high performance for the applications.

    • PL/SQL gives high productivity to programmers as it can query, transform, and update data in a database.

    • PL/SQL saves time on design and debugging by strong features, such as exception handling, encapsulation, data hiding, and object-oriented data types.

    • Applications written in PL/SQL are fully portable.

    • PL/SQL provides high security level.

    • PL/SQL provides access to predefined SQL packages.

    • PL/SQL provides support for Object-Oriented Programming.

    • PL/SQL provides support for developing Web Applications and Server Pages.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Variables nhận dự án làm có lương

    PL/SQL – Variables



    In this chapter, we will discuss Variables in Pl/SQL. A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in PL/SQL has a specific data type, which determines the size and the layout of the variable”s memory; the range of values that can be stored within that memory and the set of operations that can be applied to the variable.

    The name of a PL/SQL variable consists of a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs and should not exceed 30 characters. By default, variable names are not case-sensitive. You cannot use a reserved PL/SQL keyword as a variable name.

    PL/SQL programming language allows to define various types of variables, such as date time data types, records, collections, etc. which we will cover in subsequent chapters. For this chapter, let us study only basic variable types.

    Variable Declaration in PL/SQL

    PL/SQL variables must be declared in the declaration section or in a package as a global variable. When you declare a variable, PL/SQL allocates memory for the variable”s value and the storage location is identified by the variable name.

    The syntax for declaring a variable is −

    variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
    

    Where, variable_name is a valid identifier in PL/SQL, datatype must be a valid PL/SQL data type or any user defined data type which we already have discussed in the last chapter. Some valid variable declarations along with their definition are shown below −

    sales number(10, 2);
    pi CONSTANT double precision := 3.1415;
    name varchar2(25);
    address varchar2(100);
    

    When you provide a size, scale or precision limit with the data type, it is called a constrained declaration. Constrained declarations require less memory than unconstrained declarations. For example −

    sales number(10, 2);
    name varchar2(25);
    address varchar2(100);
    

    Initializing Variables in PL/SQL

    Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you want to initialize a variable with a value other than the NULL value, you can do so during the declaration, using either of the following −

    • The DEFAULT keyword

    • The assignment operator

    For example −

    counter binary_integer := 0;
    greetings varchar2(20) DEFAULT ''Have a Good Day
    

    You can also specify that a variable should not have a NULL value using the NOT NULL constraint. If you use the NOT NULL constraint, you must explicitly assign an initial value for that variable.

    It is a good programming practice to initialize variables properly otherwise, sometimes programs would produce unexpected results. Try the following example which makes use of various types of variables −

    DECLARE
       a integer := 10;
       b integer := 20;
       c integer;
       f real;
    BEGIN
       c := a + b;
       dbms_output.put_line(''Value of c: '' || c);
       f := 70.0/3.0;
       dbms_output.put_line(''Value of f: '' || f);
    END;
    /
    

    When the above code is executed, it produces the following result −

    Value of c: 30
    Value of f: 23.333333333333333333
    
    PL/SQL procedure successfully completed.
    

    Variable Scope in PL/SQL

    PL/SQL allows the nesting of blocks, i.e., each program block may contain another inner block. If a variable is declared within an inner block, it is not accessible to the outer block. However, if a variable is declared and accessible to an outer block, it is also accessible to all nested inner blocks. There are two types of variable scope −

    • Local variables − Variables declared in an inner block and not accessible to outer blocks.

    • Global variables − Variables declared in the outermost block or a package.

    Following example shows the usage of Local and Global variables in its simple form −

    DECLARE
       -- Global variables
       num1 number := 95;
       num2 number := 85;
    BEGIN
       dbms_output.put_line(''Outer Variable num1: '' || num1);
       dbms_output.put_line(''Outer Variable num2: '' || num2);
       DECLARE
          -- Local variables
          num1 number := 195;
          num2 number := 185;
       BEGIN
          dbms_output.put_line(''Inner Variable num1: '' || num1);
          dbms_output.put_line(''Inner Variable num2: '' || num2);
       END;
    END;
    /
    

    When the above code is executed, it produces the following result −

    Outer Variable num1: 95
    Outer Variable num2: 85
    Inner Variable num1: 195
    Inner Variable num2: 185
    
    PL/SQL procedure successfully completed.
    

    Assigning SQL Query Results to PL/SQL Variables

    You can use the SELECT INTO statement of SQL to assign values to PL/SQL variables. For each item in the SELECT list, there must be a corresponding, type-compatible variable in the INTO list. The following example illustrates the concept. Let us create a table named CUSTOMERS −

    (For SQL statements, please refer to the )

    CREATE TABLE CUSTOMERS(
       ID   INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY   DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    
    Table Created
    

    Let us now insert some values in the table −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (2, ''Khilan'', 25, ''Delhi'', 1500.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (3, ''kaushik'', 23, ''Kota'', 2000.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (5, ''Hardik'', 27, ''Bhopal'', 8500.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (6, ''Komal'', 22, ''MP'', 4500.00 );
    

    The following program assigns values from the above table to PL/SQL variables using the SELECT INTO clause of SQL −

    DECLARE
       c_id customers.id%type := 1;
       c_name  customers.name%type;
       c_addr customers.address%type;
       c_sal  customers.salary%type;
    BEGIN
       SELECT name, address, salary INTO c_name, c_addr, c_sal
       FROM customers
       WHERE id = c_id;
       dbms_output.put_line
       (''Customer '' ||c_name || '' from '' || c_addr || '' earns '' || c_sal);
    END;
    /
    

    When the above code is executed, it produces the following result −

    Customer Ramesh from Ahmedabad earns 2000
    
    PL/SQL procedure completed successfully
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Home nhận dự án làm có lương

    PL/SQL tutorial

    PL/SQL Tutorial







    PL/SQL Tutorial

    PL/SQL, which stands for Procedural Language extensions to the (SQL). It is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90”s to enhance the capabilities of SQL. PL/SQL is one of three key programming languages embedded in the Oracle Database, along with SQL itself and .

    In this tutorial, we”ll give you a great understanding of PL/SQL to proceed with the Oracle database and other advanced .

    Purpose of PL/SQL

    The purpose of PL/SQL is to merge database commands with procedural programming language. It offers more complete programming solutions for building critical applications that operate on the Oracle database.

    Features of PL/SQL

    PL/SQL has the following features −

    • PL/SQL is tightly integrated with SQL.
    • It offers extensive extensive error checking mechanisms.
    • It supports numerous for flexible data handling.
    • Includes a variety of programming structures, such as and . Includes a variety of programming structures, such as loops and conditionals.
    • It supports structured programming through functions and procedures.
    • It supports object-oriented programming, enabling more complex data handling and manipulation.
    • It supports the web application development and server pages.

    Why to learn PL/SQL?

    Learning PL/SQL is an essential skill for persons who are interested in databases and other advanced RDBMS technologies. PL/SQL offers various benefits, making it an essential skill for database developers −

    • Ease of Use: PL/SQL is straightforward to write and read, featuring block-structured syntax which simplifies programming and debugging.
    • Portability: Programs written in PL/SQL are fully portable across different Oracle databases, ensuring consistency and ease of migration.
    • Tight SQL Integration: PL/SQL is tightly integrated with SQL, allowing for efficient querying, transforming, and updating of data within a database.
    • High Performance: It reduces network traffic by sending entire blocks of statements to the database at once, thus improving performance.
    • Security: It includes robust security features to protect database integrity.
    • Object-Oriented Support: It supports object-oriented programming, and allows you to define object types that can be used in object-oriented designs.

    PL/SQL Block Structured

    PL/SQL follows a block-structured approach, dividing programs into logical blocks of code. Each block consists of three main sections −

    • Declarations: This section, starting with the keyword DECLARE, is optional and used for defining , , subprograms, and other elements required within the block.
    • Executable Commands: Enclosed between the keywords BEGIN and END, this mandatory section contains executable PL/SQL statements. It must include at least one executable line of code, even if it”s just a NULL command indicating no action.
    • Exception Handling: This starts with the keyword EXCEPTION, this optional section deals with handling errors in the program through defined exceptions.

    PL/SQL statements are terminated with a semicolon(;). Additionally, blocks can be nested within each other using BEGIN and END keywords.

    Applications of PL/SQL

    PL/SQL is widely used in various applications, including −

    • Database Security: It implements robust security measures within the database.
    • XML Management: Generating and managing XML documents within the database.
    • Linking Databases to Web Pages: Integrates databases with web applications.
    • Automation: Automating database administration tasks for efficient management.

    Who Should Learn PL/SQL?

    This tutorial is designed for Software Professionals, who are willing to learn PL/SQL Programming Language in simple and easy steps. This tutorial will give you a great understanding of PL/SQL Programming concepts, and after completing this tutorial, you will be at an intermediate level of expertise from where you can take yourself to a higher level of expertise.

    Prerequisites to learn PL/SQL

    Before proceeding with this tutorial, you should have a basic understanding of software concepts like what is database, source code, text editor, and execution of programs, etc. If you already have an understanding of SQL and other computer programming languages, then it will be an added advantage to proceed. Let”s get started!

    PL/SQL Jobs and Opportunities

    Proficiency in PL/SQL opens up various career opportunities, such as −

    • Oracle PL/SQL Programmer
    • PL/SQL Developer
    • Database Developer
    • Data Analyst
    • Database Testers
    • Data Scientist
    • ETL Developer
    • Database Migration Expert
    • Cloud Database Expert etc

    By mastering PL/SQL, you can increase your career opportunities in database management and development, as well as in creating secure and scalable applications.

    Frequently Asked Questions about PL/SQL

    There are some very Frequently Asked Questions(FAQ) about PL/SQL, this section tries to answer them briefly.

    PL/SQL records are data structures designed to hold multiple data items of different types. They consist of various fields, much like a row in a database table.

    SQL (Structured Query Language) is a standard language used for creating, manipulating, and retrieving data from relational databases. SQL is mainly used to write queries, as well as create and execute DDL (Data Definition Language) and DML (Data Manipulation Language) statements.

    Whereas, PL/SQL (Procedural Language/SQL) is an extension of SQL. And it adds procedural capabilities to SQL, enabling the creation of more complex and powerful database applications. PL/SQL supports variables, data types, and control structures such as loops and conditionals, which SQL does not. This makes PL/SQL more efficient for writing program blocks, functions, procedures, triggers, and packages.

    When an exception is raised in PL/SQL, the current PL/SQL block stops its regular execution and transfers control to the exception section. The exception is then handled by an exception handler within the current PL/SQL block or passed to the enclosing block if not handled locally.

    To manage an exception after it is raised, you need to write an exception handler for it. This handler should be placed after all executable statements in your PL/SQL block but before the END statement. The EXCEPTION keyword indicates the start of the exception-handling section.

    The best place to learn PL/SQL is through our comprehensive and user-friendly tutorial. Our PL/SQL tutorial provides an excellent starting point for understanding database programming with PL/SQL. You can explore our simple and effective learning materials at your own pace.

    A PL/SQL table, also known as an associative array or index-by table, is a collection of key-value pairs where each key is a unique index used to access the corresponding value. This table functions similarly to a relational table, storing data in rows and columns. Each column represents a different attribute or value, while each row contains individual records with values for all the columns.

    Following are some tips to learn PL/SQL −

    • The first and most crucial step is to decide to learn PL/SQL and stay committed to your goal.
    • Install the necessary tools like SQL*Plus or Oracle SQL Developer on your computer.
    • Start with our PL/SQL tutorial and progress step by step from the basics.
    • Read more articles, watch online courses, or buy a book on PL/SQL to deepen your understanding.
    • Apply what you’ve learned by developing small projects that incorporate PL/SQL and other technologies.

    SQL*Plus and PL/SQL Developer are commonly used for writing and executing PL/SQL code.

    In PL/SQL, there are two types of parameters −

    • Actual Parameters: Actual parameters are the values or expressions provided in the parameter list when calling a module. In this only the variable is mentioned, not the data types.
    • Formal Parameters: Formal parameters are the names declared in the parameter list of a module”s header.

    Learning PL/SQL is crucial for a person who is interested in databases and advanced RDBMS technologies. It offers numerous benefits, making it an essential skill for database developers. With PL/SQL, you can efficiently manipulate and manage data within Oracle databases, which increases your ability to work with large datasets and complex queries.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Data Types nhận dự án làm có lương

    PL/SQL – Data Types



    In this chapter, we will discuss the Data Types in PL/SQL. The PL/SQL variables, constants and parameters must have a valid data type, which specifies a storage format, constraints, and a valid range of values. We will focus on the SCALAR and the LOB data types in this chapter. The other two data types will be covered in other chapters.

    S.No Category & Description
    1

    Scalar

    Single values with no internal components, such as a NUMBER, DATE, or BOOLEAN.

    2

    Large Object (LOB)

    Pointers to large objects that are stored separately from other data items, such as text, graphic images, video clips, and sound waveforms.

    3

    Composite

    Data items that have internal components that can be accessed individually. For example, collections and records.

    4

    Reference

    Pointers to other data items.

    PL/SQL Scalar Data Types and Subtypes

    PL/SQL Scalar Data Types and Subtypes come under the following categories −

    S.No Date Type & Description
    1

    Numeric

    Numeric values on which arithmetic operations are performed.

    2

    Character

    Alphanumeric values that represent single characters or strings of characters.

    3

    Boolean

    Logical values on which logical operations are performed.

    4

    Datetime

    Dates and times.

    PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype called INTEGER. You can use the subtypes in your PL/SQL program to make the data types compatible with data types in other programs while embedding the PL/SQL code in another program, such as a Java program.

    PL/SQL Numeric Data Types and Subtypes

    Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −

    S.No Data Type & Description
    1

    PLS_INTEGER

    Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

    2

    BINARY_INTEGER

    Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

    3

    BINARY_FLOAT

    Single-precision IEEE 754-format floating-point number

    4

    BINARY_DOUBLE

    Double-precision IEEE 754-format floating-point number

    5

    NUMBER(prec, scale)

    Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including) 1.0E126. A NUMBER variable can also represent 0

    6

    DEC(prec, scale)

    ANSI specific fixed-point type with maximum precision of 38 decimal digits

    7

    DECIMAL(prec, scale)

    IBM specific fixed-point type with maximum precision of 38 decimal digits

    8

    NUMERIC(pre, secale)

    Floating type with maximum precision of 38 decimal digits

    9

    DOUBLE PRECISION

    ANSI specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)

    10

    FLOAT

    ANSI and IBM specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)

    11

    INT

    ANSI specific integer type with maximum precision of 38 decimal digits

    12

    INTEGER

    ANSI and IBM specific integer type with maximum precision of 38 decimal digits

    13

    SMALLINT

    ANSI and IBM specific integer type with maximum precision of 38 decimal digits

    14

    REAL

    Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits)

    Following is a valid declaration −

    DECLARE
       num1 INTEGER;
       num2 REAL;
       num3 DOUBLE PRECISION;
    BEGIN
       null;
    END;
    /
    

    When the above code is compiled and executed, it produces the following result −

    PL/SQL procedure successfully completed
    

    PL/SQL Character Data Types and Subtypes

    Following is the detail of PL/SQL pre-defined character data types and their sub-types −

    S.No Data Type & Description
    1

    CHAR

    Fixed-length character string with maximum size of 32,767 bytes

    2

    VARCHAR2

    Variable-length character string with maximum size of 32,767 bytes

    3

    RAW

    Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted by PL/SQL

    4

    NCHAR

    Fixed-length national character string with maximum size of 32,767 bytes

    5

    NVARCHAR2

    Variable-length national character string with maximum size of 32,767 bytes

    6

    LONG

    Variable-length character string with maximum size of 32,760 bytes

    7

    LONG RAW

    Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by PL/SQL

    8

    ROWID

    Physical row identifier, the address of a row in an ordinary table

    9

    UROWID

    Universal row identifier (physical, logical, or foreign row identifier)

    PL/SQL Boolean Data Types

    The BOOLEAN data type stores logical values that are used in logical operations. The logical values are the Boolean values TRUE and FALSE and the value NULL.

    However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values cannot be used in −

    • SQL statements
    • Built-in SQL functions (such as TO_CHAR)
    • PL/SQL functions invoked from SQL statements

    PL/SQL Datetime and Interval Types

    The DATE datatype is used to store fixed-length datetimes, which include the time of day in seconds since midnight. Valid dates range from January 1, 4712 BC to December 31, 9999 AD.

    The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT. For example, the default might be ”DD-MON-YY”, which includes a two-digit number for the day of the month, an abbreviation of the month name, and the last two digits of the year. For example, 01-OCT-12.

    Each DATE includes the century, year, month, day, hour, minute, and second. The following table shows the valid values for each field −

    Field Name Valid Datetime Values Valid Interval Values
    YEAR -4712 to 9999 (excluding year 0) Any nonzero integer
    MONTH 01 to 12 0 to 11
    DAY 01 to 31 (limited by the values of MONTH and YEAR, according to the rules of the calendar for the locale) Any nonzero integer
    HOUR 00 to 23 0 to 23
    MINUTE 00 to 59 0 to 59
    SECOND 00 to 59.9(n), where 9(n) is the precision of time fractional seconds 0 to 59.9(n), where 9(n) is the precision of interval fractional seconds
    TIMEZONE_HOUR -12 to 14 (range accommodates daylight savings time changes) Not applicable
    TIMEZONE_MINUTE 00 to 59 Not applicable
    TIMEZONE_REGION Found in the dynamic performance view V$TIMEZONE_NAMES Not applicable
    TIMEZONE_ABBR Found in the dynamic performance view V$TIMEZONE_NAMES Not applicable

    PL/SQL Large Object (LOB) Data Types

    Large Object (LOB) data types refer to large data items such as text, graphic images, video clips, and sound waveforms. LOB data types allow efficient, random, piecewise access to this data. Following are the predefined PL/SQL LOB data types −

    Data Type Description Size
    BFILE Used to store large binary objects in operating system files outside the database. System-dependent. Cannot exceed 4 gigabytes (GB).
    BLOB Used to store large binary objects in the database. 8 to 128 terabytes (TB)
    CLOB Used to store large blocks of character data in the database. 8 to 128 TB
    NCLOB Used to store large blocks of NCHAR data in the database. 8 to 128 TB

    PL/SQL User-Defined Subtypes

    A subtype is a subset of another data type, which is called its base type. A subtype has the same valid operations as its base type, but only a subset of its valid values.

    PL/SQL predefines several subtypes in package STANDARD. For example, PL/SQL predefines the subtypes CHARACTER and INTEGER as follows −

    SUBTYPE CHARACTER IS CHAR;
    SUBTYPE INTEGER IS NUMBER(38,0);
    

    You can define and use your own subtypes. The following program illustrates defining and using a user-defined subtype −

    DECLARE
       SUBTYPE name IS char(20);
       SUBTYPE message IS varchar2(100);
       salutation name;
       greetings message;
    BEGIN
       salutation := ''Reader
       greetings := ''Welcome to the World of PL/SQL
       dbms_output.put_line(''Hello '' || salutation || greetings);
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    Hello Reader Welcome to the World of PL/SQL
    
    PL/SQL procedure successfully completed.
    

    NULLs in PL/SQL

    PL/SQL NULL values represent missing or unknown data and they are not an integer, a character, or any other specific data type. Note that NULL is not the same as an empty data string or the null character value ””. A null can be assigned but it cannot be equated with anything, including itself.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Loops nhận dự án làm có lương

    PL/SQL – Loops



    In this chapter, we will discuss Loops in PL/SQL. There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

    Programming languages provide various control structures that allow for more complicated execution paths.

    A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −

    Loop Architecture

    PL/SQL provides the following types of loop to handle the looping requirements. Click the following links to check their detail.

    S.No Loop Type & Description
    1

    In this loop structure, sequence of statements is enclosed between the LOOP and the END LOOP statements. At each iteration, the sequence of statements is executed and then control resumes at the top of the loop.

    2

    Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

    3

    Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

    4

    You can use one or more loop inside any another basic loop, while, or for loop.

    Labeling a PL/SQL Loop

    PL/SQL loops can be labeled. The label should be enclosed by double angle brackets (<< and >>) and appear at the beginning of the LOOP statement. The label name can also appear at the end of the LOOP statement. You may use the label in the EXIT statement to exit from the loop.

    The following program illustrates the concept −

    DECLARE
       i number(1);
       j number(1);
    BEGIN
       << outer_loop >>
       FOR i IN 1..3 LOOP
          << inner_loop >>
          FOR j IN 1..3 LOOP
             dbms_output.put_line(''i is: ''|| i || '' and j is: '' || j);
          END loop inner_loop;
       END loop outer_loop;
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    i is: 1 and j is: 1
    i is: 1 and j is: 2
    i is: 1 and j is: 3
    i is: 2 and j is: 1
    i is: 2 and j is: 2
    i is: 2 and j is: 3
    i is: 3 and j is: 1
    i is: 3 and j is: 2
    i is: 3 and j is: 3
    
    PL/SQL procedure successfully completed.
    

    The Loop Control Statements

    Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

    PL/SQL supports the following control statements. Labeling loops also help in taking the control outside a loop. Click the following links to check their details.

    S.No Control Statement & Description
    1

    The Exit statement completes the loop and control passes to the statement immediately after the END LOOP.

    2

    Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

    3

    Transfers control to the labeled statement. Though it is not advised to use the GOTO statement in your program.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Conditions nhận dự án làm có lương

    PL/SQL – Conditions



    In this chapter, we will discuss conditions in PL/SQL. Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

    Following is the general form of a typical conditional (i.e., decision making) structure found in most of the programming languages −

    Decision making statements in PL/SQL

    PL/SQL programming language provides following types of decision-making statements. Click the following links to check their detail.

    S.No Statement & Description
    1

    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.

    2

    IF statement adds the keyword ELSE followed by an alternative sequence of statement. If the condition is false or NULL, then only the alternative sequence of statements get executed. It ensures that either of the sequence of statements is executed.

    3

    It allows you to choose between several alternatives.

    4

    Like the IF statement, the CASE statement selects one sequence of statements to execute.

    However, to select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions. A selector is an expression whose value is used to select one of several alternatives.

    5

    The searched CASE statement has no selector, and it”s WHEN clauses contain search conditions that yield Boolean values.

    6

    You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-THEN-ELSIF statement(s).


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Environment nhận dự án làm có lương

    PL/SQL – Environment Setup



    In this chapter, we will discuss the Environment Setup of PL/SQL. PL/SQL is not a standalone programming language; it is a tool within the Oracle programming environment. SQL* Plus is an interactive tool that allows you to type SQL and PL/SQL statements at the command prompt. These commands are then sent to the database for processing. Once the statements are processed, the results are sent back and displayed on screen.

    To run PL/SQL programs, you should have the Oracle RDBMS Server installed in your machine. This will take care of the execution of the SQL commands. The most recent version of Oracle RDBMS is 11g. You can download a trial version of Oracle 11g from the following link −

    You will have to download either the 32-bit or the 64-bit version of the installation as per your operating system. Usually there are two files. We have downloaded the 64-bit version. You will also use similar steps on your operating system, does not matter if it is Linux or Solaris.

    • win64_11gR2_database_1of2.zip

    • win64_11gR2_database_2of2.zip

    After downloading the above two files, you will need to unzip them in a single directory database and under that you will find the following sub-directories −

    Oracle Sub Directries

    Step 1

    Let us now launch the Oracle Database Installer using the setup file. Following is the first screen. You can provide your email ID and check the checkbox as shown in the following screenshot. Click the Next button.

    Oracle Install 1

    Step 2

    You will be directed to the following screen; uncheck the checkbox and click the Continue button to proceed.

    Oracle install error

    Step 3

    Just select the first option Create and Configure Database using the radio button and click the Next button to proceed.

    Oracle Install 2

    Step 4

    We assume you are installing Oracle for the basic purpose of learning and that you are installing it on your PC or Laptop. Thus, select the Desktop Class option and click the Next button to proceed.

    Oracle Install 3

    Step 5

    Provide a location, where you will install the Oracle Server. Just modify the Oracle Base and the other locations will set automatically. You will also have to provide a password; this will be used by the system DBA. Once you provide the required information, click the Next button to proceed.

    Oracle Install 4

    Step 6

    Again, click the Next button to proceed.

    Oracle Install 5

    Step 7

    Click the Finish button to proceed; this will start the actual server installation.

    Oracle Install 6

    Step 8

    This will take a few moments, until Oracle starts performing the required configuration.

    Oracle Install 7

    Step 9

    Here, Oracle installation will copy the required configuration files. This should take a moment −

    Oracle Configuration

    Step 10

    Once the database files are copied, you will have the following dialogue box. Just click the OK button and come out.

    Oracle Configuration

    Step 11

    Upon installation, you will have the following final window.

    Oracle Install 8

    Final Step

    It is now time to verify your installation. At the command prompt, use the following command if you are using Windows −

    sqlplus "/ as sysdba"
    

    You should have the SQL prompt where you will write your PL/SQL commands and scripts −

    PL/SQL Command Prompt

    Text Editor

    Running large programs from the command prompt may land you in inadvertently losing some of the work. It is always recommended to use the command files. To use the command files −

    • Type your code in a text editor, like Notepad, Notepad+, or EditPlus, etc.

    • Save the file with the .sql extension in the home directory.

    • Launch the SQL*Plus command prompt from the directory where you created your PL/SQL file.

    • Type @file_name at the SQL*Plus command prompt to execute your program.

    If you are not using a file to execute the PL/SQL scripts, then simply copy your PL/SQL code and right-click on the black window that displays the SQL prompt; use the paste option to paste the complete code at the command prompt. Finally, just press Enter to execute the code, if it is not already executed.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Constants and Literals nhận dự án làm có lương

    PL/SQL – Constants and Literals



    In this chapter, we will discuss constants and literals in PL/SQL. A constant holds a value that once declared, does not change in the program. A constant declaration specifies its name, data type, and value, and allocates storage for it. The declaration can also impose the NOT NULL constraint.

    Declaring a Constant

    A constant is declared using the CONSTANT keyword. It requires an initial value and does not allow that value to be changed. For example −

    PI CONSTANT NUMBER := 3.141592654;
    DECLARE
       -- constant declaration
       pi constant number := 3.141592654;
       -- other declarations
       radius number(5,2);
       dia number(5,2);
       circumference number(7, 2);
       area number (10, 2);
    BEGIN
       -- processing
       radius := 9.5;
       dia := radius * 2;
       circumference := 2.0 * pi * radius;
       area := pi * radius * radius;
       -- output
       dbms_output.put_line(''Radius: '' || radius);
       dbms_output.put_line(''Diameter: '' || dia);
       dbms_output.put_line(''Circumference: '' || circumference);
       dbms_output.put_line(''Area: '' || area);
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    Radius: 9.5
    Diameter: 19
    Circumference: 59.69
    Area: 283.53
    
    Pl/SQL procedure successfully completed.
    

    The PL/SQL Literals

    A literal is an explicit numeric, character, string, or Boolean value not represented by an identifier. For example, TRUE, 786, NULL, ”tutorialspoint” are all literals of type Boolean, number, or string. PL/SQL, literals are case-sensitive. PL/SQL supports the following kinds of literals −

    • Numeric Literals
    • Character Literals
    • String Literals
    • BOOLEAN Literals
    • Date and Time Literals

    The following table provides examples from all these categories of literal values.

    S.No Literal Type & Example
    1

    Numeric Literals

    050 78 -14 0 +32767

    6.6667 0.0 -12.0 3.14159 +7800.00

    6E5 1.0E-8 3.14159e0 -1E38 -9.5e-3

    2

    Character Literals

    ”A” ”%” ”9” ” ” ”z” ”(”

    3

    String Literals

    ”Hello, world!”

    ”Tutorials Point”

    ”19-NOV-12”

    4

    BOOLEAN Literals

    TRUE, FALSE, and NULL.

    5

    Date and Time Literals

    DATE ”1978-12-25

    TIMESTAMP ”2012-10-29 12:01:01

    To embed single quotes within a string literal, place two single quotes next to each other as shown in the following program −

    DECLARE
       message  varchar2(30):= ''That''''s tutorialspoint.com!
    BEGIN
       dbms_output.put_line(message);
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    That''s tutorialspoint.com!
    
    PL/SQL procedure successfully completed.
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc