unit-1 introduction to plsql

Post on 11-Feb-2016

244 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

PLSQLbhjhjbjh

TRANSCRIPT

Unit-1 Introduction to PL/SQL

Why need PL/SQL?

• Disadvantages of SQL, when used as a conventional programming language.

– SQL does not have any procedural capabilities i.e. SQL does not

provide the programming techniques of condition checking, looping and branching that is vital for data testing before its permanent storage.

– SQL statement are passed to the oracle Engine one at a time. Each time an SQL statement executed, a call is made to the engine’s resources. This add to the traffic on the network, thereby decreasing the speed of data processing, especially in a multi-user environment .

– While processing SQL statement if an error occurs, the Oracle Engine displays its own error message. SQL has no facility for programmed handling of error that arise during the manipulation of data.

• Although SQL is a very powerful tool, its set of disadvantages prevent, it from being a fully structured programming language.

• For fully structured programming language, Oracle provide PL/SQL.

What is PL/SQL ??

• PL/SQL stands for Procedural Language extension of SQL.

• PL/SQL is a block-structured language that enables developers to combine the power of SQL with procedural statement.

• PL/SQL 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.

The PL/SQL Engine:

• Oracle uses a PL/SQL engine to processes the PL/SQL statements.

• Every PL/SQL block is first executed by PL/SQL engine. This PL/SQL engine that compiles and executes PL/SQL blocks.

• PL/SQL engine executes all procedural statements of a PL/SQL block, but sends SQL command to SQL statements executor in the Oracle RDBMS.

• That means PL/SQL Engine separates SQL commands from PL/SQL block and executes PL/SQL commands / statement using Procedural statement executor, which is a part of PL/SQL engine.

• A PL/SQL code can be stored in the client system (client-side) or in the database (server-side).

A Simple PL/SQL Block:

• Each PL/SQL program consists of SQL and PL/SQL statements which form a PL/SQL block.

• A PL/SQL Block consists of three sections:

– The Declaration section (optional).

– The Execution section (mandatory).

– The Exception (or Error) Handling section (optional).

Declaration Section:

• The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.

• This section is optional and is used to declare any placeholders like variables, constants, records and cursors, which are used to manipulate data in the execution section.

• Placeholders may be any of Variables, Constants and Records, which stores data temporarily.

• E.g. – name_v varchar2(30); – sum_v number(4);

Execution Section:

• The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END.

• This is a mandatory section and is the section where the program logic is written to perform any task.

• The programmatic constructs like loops, conditional statement and SQL statements are the part of execution section.

Exception Section:

• The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION.

• This section is optional.

• Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates gracefully.

• If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abnormally with errors.

PL/ SQL Block Execution

Advantages of PL/SQL Block • Block Structures: PL SQL consists of blocks of code, which can be

nested within each other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be stored and reused.

• Procedural Language Capability: PL SQL consists of procedural

language constructs such as conditional statements (if else statements) and loops like (FOR loops).

• Better Performance: PL SQL engine processes multiple SQL

statements simultaneously as a single block, thereby reducing network traffic and increasing performance.

• Error Handling: PL/SQL handles errors or exceptions effectively during

the execution of a PL/SQL program. Once an exception is caught, specific actions can be taken depending upon the type of the exception or it can be displayed to the user with a message.

PL/SQL The Character set

• The basic character set includes the following: – Uppercase alphabets {A-Z} – Lowercase alphabets {a-z} – Numerals {0-9} – Symbols ( ) + - * / < > = ! ; : . ’ @ % , ” # $ ^ & _ \ { } ? ||

• Words used in a PL/SQL block are called lexical Units. • Blank space can be freely inserted between lexical

units in a PL/SQL block. • The blank spaces have no effect on the PL/SQL block.

Literals

• A literals is a numeric value or a character string to represent itself

• Numeric literals

– This can be either integers or floats.

– If a float is being represented, then the integer part must be separated from the float part by a period.

– E.g. 25, 6.34, 25e-3, .1, 1.e4, +17 ,-5

• String Literal

– These can be represented by one or more legal characters and must be enclosed within single quotes.

– The single quote character can be represented, by writing it twice in a string literal.

– This is definitely not the same as a double quote.

– E.g.

• ‘hello world’

• ‘Don’’t go without saving your work’

• Character literal

– These are string literals consisting of single character.

– E.g. ‘*’, ‘A’, ‘y’

• Logical (Boolean) Literal

– These are predetermined constants.

– The values that can be assigned to this data type are: TRUE, FALSE, NULL.

PL/ SQL data types

• Default data type that can be declared are number ( numeric data), varchar2 ( Number Character data), char, date( date and time). All this data type can have NULL values.

• %TYPE attribute to declare variables based on definitions of columns in a table. If column’s attributes change, the variable’s attribute will change as well.

• E.g Name_v Employee.name%TYPE

VariableName TableColumnNameType

Variables • Variables:

– Variables are named part of a PL/SQL block, used to store a data value.

– Name must begin with a character and can be followed by a max of 29 characters.

– Space and reserved words can’t be used as variable names.

– General Syntax to declare a variable is variable_name datatype [NOT NULL := value ];

• variable_name is the name of the variable. • datatype is a valid PL/SQL datatype. • NOT NULL is an optional specification on the variable. • value or DEFAULT values also an optional specification, where you can

initialize a variable. • Each variable declaration is a separate statement and must be

terminated by a semicolon.

• For example, if you want to store the current salary of an employee, you can use a variable. DECLARE salary number (6); – “salary” is a variable of data type number and of length 6.

• When a variable is specified as NOT NULL, you must initialize the variable when it is declared.

• For example: The below example declares two variables, one of which is a not null. – DECLARE – salary number(4); – dept varchar2(10) NOT NULL := ‘HR Dept’;

• The value of a variable can change in the execution or exception section of the PL/SQL Block.

• NOT NULL causes creation of a variable or a constant that can not be assigned the value null value. – dept:=‘’;

• We can assign values to variables in the two ways given below.

1) We can directly assign values to variables.

The General Syntax is: variable_name:= value; 2) We can assign values to variables directly from the

database columns by using a SELECT..INTO statement. The General Syntax is:

SELECT column_name INTO variable_name FROM table_name [WHERE condition];

PL/SQL-Practical

Starting with ‘Hello World’

BEGIN

DBMS_OUTPUT.PUT_LINE(’Hello World’);

END;

• DBMS_OUTPUT.PUT_LINE() as sort of a printf() in C language

• It writes output to the console; but it only works for strings (or data that can be implicitly converted to a string).

Display System Date

• To display system date use global variable SYSDATE .

• E.g. BEGIN DBMS_OUTPUT.PUT_LINE(’The Date now is:

’); DBMS_OUTPUT.PUT_LINE(SYSDATE); END; • Output: The Date now is: 13-AUG-13

Cont… • To change the date format use the function

TO_CHAR(Date,Format)

• E.g

BEGIN

DBMS_OUTPUT.PUT_LINE(’The Date now is: ’);

DBMS_OUTPUT.PUT_LINE(TO_CHAR(SYSDATE, ’MM/DD/YYYY’));

END;

Output:

The Date now is:

08/13/2013

String Concatenation Operator(||)

• To concate one or more string ‘||’ (two times pipe sign)concatenation operator is used.

• For Example:

– Begin

• Dbms_output.put_line(‘Hello World’||’ How are You??’);

– End;

PL/SQL - Operators • Arithmetic operators:-

– Following table shows all the arithmetic operators supported by PL/SQL. Assume variable A holds 10 and variable B holds 5 then:

Operator Description Example

+ Adds two operands A + B will give 15

- Subtracts second operand from the first A - B will give 5

* Multiplies both operands A * B will give 50

/ Divides numerator by de-numerator A / B will give 2

** Exponentiation operator, raises one operand to the power of other

A ** B will give 100000

• Relational operators

• Relational operators compare two expressions or values and return a Boolean result. Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example

= Checks if the values of two operands are equal or not, if yes then condition becomes true.

(A = B) is not true.

!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

(A != B) is true.

> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

• Comparison operators – Comparison operators are used for comparing

one expression to another. The result is always either TRUE, FALSE OR NULL.

Operator Description Example

LIKE The LIKE operator compares a character or string value to a pattern and returns TRUE if the value matches the pattern and FALSE if it does not.

If 'Zara Ali' like 'Z% A_i' returns a Boolean true, whereas, 'Nuha Ali' like 'Z% A_i' returns a Boolean false.

BETWEEN The BETWEEN operator tests whether a value lies in a specified range. x BETWEEN a AND b means that x >= a and x <= b.

If x = 10 then, x between 5 and 20 returns true, x between 5 and 10 returns true, but x between 11 and 20 returns false.

IN The IN operator tests set membership. x IN (set) means that x is equal to any member of set.

If x = 'm' then, x in ('a', 'b', 'c') returns boolean false but x in ('m', 'n', 'o') returns Boolean true.

IS NULL The IS NULL operator returns the BOOLEAN value TRUE if its operand is NULL or FALSE if it is not NULL. Comparisons involving NULL values always yield NULL.

If x = 'm', then 'x is null' returns Boolean false.

• Logical operators

– Logical operators work on Boolean operands and produces Boolean results. Assume variable A holds true and variable B holds false, then:

Operator Description Example

and Called logical AND operator. If both the operands are true then condition becomes true.

(A and B) is false.

or Called logical OR Operator. If any of the two operands is true then condition becomes true.

(A or B) is true.

not Called logical NOT Operator. Used to reverse the logical state of its operand. If a condition is true then Logical NOT operator will make it false.

not (A and B) is true.

PL/SQL Conditions

PL/SQL IF Statement

• IF - THEN Structure

• 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.

• The general format of IF statement is:

IF condition THEN

program_statements

END IF;

Example:

DECLARE

A NUMBER(6);

B NUMBER(6);

BEGIN

A := 23;

B := A * 5;

IF A < B THEN

DBMS_OUTPUT.PUT_LINE(’Ans: ’ || A || ’ is less than ’ || B);

END IF;

END;

IF - ELSE Structure

• Just as in any programming language that has an IF statement, there is also the ELSE clause to the IF statement. 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.

• The full structure of an IF statement is thus:

IF condition THEN

S1;

ELSE

S2;

END IF;

Example:

IF color = red THEN

dbms_output.put_line('You have chosen a red car');

ELSE

dbms_output.put_line('Please choose a color ');

END IF;

IF-THEN-ELSIF • The IF-THEN-ELSIF statement allows you to

choose between several alternatives. An IF-THEN statement can be followed by an optional ELSIF...ELSE statement.

• When using IF-THEN-ELSIF statements there are few points to keep in mind. – It's ELSIF, not ELSEIF

– An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's.

– An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE.

– Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.

Syntax:

IF(boolean_expression 1)THEN S1; -- Executes when the boolean expression 1 is true

ELSIF( boolean_expression 2) THEN

S2; -- Executes when the boolean expression 2 is true

ELSIF( boolean_expression 3) THEN

S3; -- Executes when the boolean expression 3 is true

ELSE

S4; -- executes when the none of the above condition is true

END IF;

Example: DECLARE a number(3) := 100; BEGIN IF ( a = 10 ) THEN

dbms_output.put_line('Value of a is 10' ); ELSIF ( a = 20 ) THEN dbms_output.put_line('Value of a is 20' ); ELSIF ( a = 30 ) THEN dbms_output.put_line('Value of a is 30' ); ELSE dbms_output.put_line('None of the values is matching'); END IF; dbms_output.put_line('Exact value of a is: '|| a );

END;

Nested IF ELSE

• use one IF or ELSE IF statement inside another IF or ELSE IF statement(s).

Syntax:

IF( boolean_expression 1)THEN -- executes when the boolean expression 1 is true IF(boolean_expression 2) THEN -- executes when the boolean expression 2 is true

sequence-of-statements; END IF; ELSE -- executes when the boolean expression 1 is not

true else-statements; END IF;

Example

• DECLARE a number(3) := 100; b number(3) := 200; BEGIN -- check the boolean condition IF( a = 100 ) THEN -- if condition is true then check the following IF( b = 200 ) THEN -- if condition is true then print the following

dbms_output.put_line('Value of a is 100 and b is 200' );

END IF; END IF; dbms_output.put_line('Exact value of a is : ' || a );

dbms_output.put_line('Exact value of b is : ' || b ); END;

PL/SQL - CASE Statement

• 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.

Syntax:

CASE selector

WHEN ‘Condition1' THEN S1;

WHEN 'Condition2' THEN S2;

WHEN 'Condition3' THEN S3;

...

ELSE Sn; -- default case

END CASE;

• Selector is the value that you are comparing to the list of conditions. (ie: condition_1, condition_2, ... condition_n)

• Conditions are evaluated in the order listed. Once a condition is found to be true, the CASE statement will return the result and not evaluate the conditions any further.

• S1 to S n, this is the value returned once a condition is found to be true.

• If no condition is found to be true, then the CASE statement will return the value in the ELSE clause.

• If the ELSE clause is omitted and no condition is found to be true, then the CASE statement will return NULL.

• You can have up to 255 comparisons in a CASE statement. Each WHEN ... THEN clause is considered 2 comparisons.

Example:

DECLARE grade varchar2(20) := 'ABCA'; BEGIN CASE grade when 'ABCA' then dbms_output.put_line('Excellent'); when 'B' then dbms_output.put_line('Very good'); when 'C' then dbms_output.put_line('Well done'); when 'D' then dbms_output.put_line('You passed'); when 'F' then dbms_output.put_line('Better try again'); else dbms_output.put_line('No such grade'); END CASE; END;

DECLARE grade number(2) :=2; BEGIN CASE grade when 1 then dbms_output.put_line('Excellent'); when 2 then dbms_output.put_line('Very good'); when 3 then dbms_output.put_line('Well done'); when 5 then dbms_output.put_line('You passed'); when 4 then dbms_output.put_line('Better try again'); else dbms_output.put_line('No such grade'); END CASE; END;

PL/SQL Loops

• 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.

• 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:

Basic loop

• Basic loop structure encloses sequence of statements in between the LOOP and END LOOP statements. With each iteration, the sequence of statements is executed and then control resumes at the top of the loop.

• Syntax: LOOP

Sequence of statements;

END LOOP;

• Here, sequence of statement(s) may be a single statement or a block of statements. An EXIT statement or an EXIT WHEN statement is required to break the loop.

DECLARE x number := 10; BEGIN LOOP dbms_output.put_line(x); x := x + 10; IF x > 50 THEN exit; END IF; END LOOP; -- after exit, control resumes here dbms_output.put_line('After Exit x is: ' || x); END;

LOOP…EXIT WHEN

DECLARE

x number := 10;

BEGIN

LOOP

dbms_output.put_line(x);

x := x + 10;

Exit WHEN x > 50;

END LOOP;

-- after exit, control resumes here

dbms_output.put_line('After Exit x is: ' || x);

END;

While Loop

• A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement as long as a given condition is true.

• Syntax:

WHILE condition LOOP sequence_of_statements

END LOOP;

DECLARE

a number(2) := 10;

BEGIN

WHILE a < 20 LOOP

dbms_output.put_line('value of a: ' || a);

a := a + 1;

END LOOP;

END;

FOR LOOP • The FOR loop executes for a specified number of

times, defined in the loop definition. Because the number of loops is specified, the overhead of checking a condition to exit is eliminated.

• The number of executions is defined in the loop definition as a range from a start value to an end value.

• The integer index in the FOR loop starts at the start value and increments by one (1) for each loop until it reaches the end value.

– FOR counter IN initial_value .. final_value LOOP

sequence_of_statements;

END LOOP;

begin for i in 2..5 loop dbms_output.put_line(i); end loop; end;

• OUTPUT: 2 3 4 5

• Notice that we never actually directly initialized i, or even declare it! It is done implicitly

• You can also use another variable to loop on.

• In the example below a variable idx is defined, assigning it the value 100.

• When the FOR loop executes, the variable idx is also defined as the index for the FOR loop.

• The original variable idx goes out of scope when the FOR loop defines its index variable.

• Inside the FOR loop, the idx variable is the loop index. Once the FOR loop terminates, the loop index goes out of scope and the original idx variable is again in scope.

declare idx number(3):=100; begin dbms_output.put_line(idx); for idx in 2..5 loop dbms_output.put_line(idx); end loop; dbms_output.put_line(idx); end; OUTPUT: 100 2 3 4 5 100

• You can use the loop index inside the loop, but you can not change it. If you try to change it, it gives you an error.

• If you want to loop by an increment other than one, you will have to do so programmatically as the FOR loop will only increment the index by one. begin

for idx in 2..400

loop

--idx:=idx+4;

dbms_output.put_line(idx);

end loop;

end;

• The loop index start and stop values can be expressions or variables.

• They are evaluated once at the start of the loop to determine the number of loop iterations.

• If their values change during the loop processing, it does not impact the number of iterations. declare var_start number:=2; var_end number:=10; begin for idx in var_start..var_end loop var_end:=20; dbms_output.put_line(idx); end loop; end;

• The loop index start and stop values are always defined from lowest to highest.

• If you want the index to count down use the REVERSE key word. begin for idx in 2..7 loop dbms_output.put_line(idx); end loop; for idx in REVERSE 2..7 loop dbms_output.put_line(idx); end loop; for idx in 7..2 loop dbms_output.put_line(idx); end loop; end;

• Notice that the third FOR loop COMPILED BUT DID NOT EXECUTE! The FOR loop calculated the number of loop iterations and got a negative number, therefore the loop count was zero.

Exit…When in FOR loop DECLARE

v1 NUMBER := 5;

BEGIN

FOR i IN 1..12

LOOP

v1 := v1 +5;

DBMS_OUTPUT.PUT_LINE(v1);

EXIT WHEN v1 > 50;

END LOOP;

END;

count(*) in FOR loop.

declare

n number;

begin

select count(*) into n from stud_r;

for i in 1..n

loop

dbms_output.put_line(i);

end loop;

end;

Character String Function

declare nm varchar2(30); nm1 varchar2(30); begin nm:=' hello'; nm1:='HELLOWORLD'; dbms_output.put_line(length(nm)); dbms_output.put_line(lower(nm1)); dbms_output.put_line(upper(nm)); dbms_output.put_line(substr(nm,4,1)); dbms_output.put_line(substr(nm1,4,5)); end;

top related